Tips on pausing until another function completes using async functions

Is there a way to ensure that my Angular functions are executed sequentially in the ngOnInit() lifecycle hook? I attempted to use async, but it didn't work as expected...

  1. nbPage()
  2. getAllCommerces(page)
  3. sort()
  4. getCommerces(isFirstLoad, event)
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { GeolocationService } from '../services/geolocation.service';

@Component({
  selector: 'app-commerces',
  templateUrl: './commerces.page.html',
  styleUrls: ['./commerces.page.scss'],
})
export class CommercesPage implements OnInit {

  itemListData = [];
  commerces = [];
  nbCommerce = 10;


  constructor(
    private httpClient: HttpClient,
    private geolocationService: GeolocationService
  ) {
  }

  async ngOnInit() {
    await this.getAllCommerces(await this.nbPage());
    await this.getCommerces(false, "");
  }


  async getCommerces(isFirstLoad, event) {

    var tmp = [];
    for (let i = 0; i < 10; i++) {
      tmp.push(this.itemListData[i]);
    }
    this.nbCommerce = + 10
    if (isFirstLoad) {
      event.target.complete();
    }

    this.commerces = tmp;
  }

  doInfinite(event) {
    this.getCommerces(true, event);
  }

  async sort() {
    this.itemListData.sort(function (a, b) {
      if (a.title.rendered > b.title.rendered)
        return 1;
      if (a.title.rendered < b.title.rendered)
        return -1;
      else
        return 0;
    });
  }

  onSearchChange(event) {
    console.log(event.detail.value);
  }


  async nbPage() {
    const t = this.httpClient
      .get('https://example.com/wp-json/wp/v2/listing', { observe: 'response' }).toPromise();

    return (await t).headers.get('X-WP-TotalPages');
  }

  async getAllCommerces(pages) {
    for (let j = 1; j <= pages; j++) {
      this.httpClient
        .get('https://example.com/wp-json/wp/v2/listing?page=' + j, { observe: 'response' })
        .subscribe((data: any) => {
          for (let i = 0; i < data.body.length; i++) {
            data.body[i].location = this.geolocationService.getDistance(data.body[i]._geolocation_lat, data.body[i]._geolocation_long).toFixed(2);;
            data.body[i]._gallery = data.body[i]._gallery[Object.keys(data.body[i]._gallery)[0]]
            this.itemListData.push(data.body[i]);
          }

        })
    }
    await this.sort();
  }
}


If you have any suggestions on how to achieve this sequential function execution in Ionic and Angular, please share your thoughts.

Answer №1

It's important to include code similar to the following:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { GeolocationService } from '../services/geolocation.service';

@Component({
  selector: 'app-commerces',
  templateUrl: './commerces.page.html',
  styleUrls: ['./commerces.page.scss'],
})
export class CommercesPage implements OnInit {

  itemListData = [];
  commerces = [];
  nbCommerce = 10;


  constructor(
    private httpClient: HttpClient,
    private geolocationService: GeolocationService
  ) {
  }


async ngOnInit(){
    this.nbPages = await this.nbPage();
    await this.getAllCommerces(this.nbPages);
    this.getCommerces(false, null);
}


  getCommerces(isFirstLoad, event) {

    var tmp = [];
    for (let i = 0; i < 10; i++) {
      tmp.push(this.itemListData[i]);
    }
    this.nbCommerce = + 10
    if (isFirstLoad) {
      event && event.target.complete();
    }

    this.commerces = tmp;
  }

  doInfinite(event) {
    this.getCommerces(true, event);
  }

  sort() {
    this.itemListData.sort(function (a, b) {
      if (a.title.rendered > b.title.rendered)
        return 1;
      if (a.title.rendered < b.title.rendered)
        return -1;
      else
        return 0;
    });
  }

  onSearchChange(event) {
    console.log(event.detail.value);
  }



async nbPage() : Promise<number>
 {
    const t = await this.httpClient
      .get('https://example.fr/wp-json/wp/v2/listing', {observe: 'response'})
      .toPromise();
      const pages = <number>parseInt(t.headers.get('X-WP-TotalPages'));
    return pages;
  }

      async getAllCommerces(pages) {
        let commerces = [];
        for (let j = 1; j <= pages; j++) {
          const response = await this.httpClient
            .get('https://exemple.fr/wp-json/wp/v2/listing?page=' + j, { observe: 'response' }).toPromise()
          for (let i = 0; i < Object.keys(response.body).length; i++) {
                response.body[i].location = await this.geolocationService.getDistance(response.body[i]._geolocation_lat, response.body[i]._geolocation_long).toFixed(2);;
                response.body[i]._gallery = response.body[i]._gallery[Object.keys(response.body[i]._gallery)[0]]
                this.itemListData.push(response.body[i]);
          }
        }
        this.sort();
      }
}

Remember that both sort and getCommerces functions are not asynchronous.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with firebase admin code completions not functioning properly in vscode?

I've attempted to install the Typescript integration for Firebase using: npm install --save-dev @types/firebase Unfortunately, I have not had any success. The "firebase-admin" and "firebase-functions" packages do not provide code completion or intel ...

The message of error is undetermined

Can someone help me with using the errorMessage object from routes in a partial? I have attempted to implement it as shown below: Route:- const express = require("express"); const router = express.Router(); const Character = require("../models/character" ...

Is it possible to create a custom range slider using Angular Material 2?

Can Angular Material 2 be used to create a custom range slider? For example, I want to display organization sizes with specific ranges like: 1-10 employees 11-50 employees 51-200 employees 201-500 employees 501-1,000 employees 1,001-5,000 employees 5,001 ...

Setting up ESLint for TypeScript to enforce the "no-unused-vars" rule

In all my TypeScript projects, I utilize ESLint with specific settings in place: "extends": ["airbnb", "prettier", 'plugin:vue/recommended'], "plugins": ["prettier"], "parserOptions&quo ...

Having difficulty launching the sapper app in production mode

Having trouble starting my sapper project in production mode. When running npm run start, the following output appears on the console: niklas@Niklass-iMac project-name % npm run start > [email protected] start /Users/niklas/path/to/project > node _ ...

`Active the button once user checks one or more checkboxes using AngularJS`

I'm working on a project where I have checkboxes and a button. I need to figure out how to activate the button when one or more checkboxes are checked using AngularJS. Can anyone provide some guidance? <script src="https://ajax.googleapis.com/aj ...

Issue with ng2-img-cropper in Angular 2: Unable to crop images from a URL

I need help with ng2-img-cropper for cropping a photo (not an avatar). You can find the library here: https://github.com/cstefanache/angular2-img-cropper I tried following this example: https://embed.plnkr.co/V91mKCNkBQZB5QO2MUP4/ It seems that the libra ...

Compiling fails when creating an object literal with a generic key

I am attempting to accomplish the following task. function createRecord<T extends string>(key: T) : Record<T, T> { return {[key]: key}; // Type '{ [x: string]: T; }' is not assignable to type 'Record<T, T>' } Howe ...

Changing route patterns in NextJS

When deploying a new NextJS app, it is important to preserve legacy routes from the old non-NextJS site. The current setup uses /const-string-[long-unique-hash] for an httpd conf redirect: For example: RewriteRule ^const-string-(.*)$ https://google.com?q ...

Tips for accessing several FormGroups within an Angular Reactive Form

Wondering if there is a method in Angular Reactive to access all FormGroups on the parent component. When I set a custom component that creates a new FormGroup within its own component, it does not reflect on the parent component. Is there a way to retri ...

converting JSON data fetched from an API into state using setState

My goal is to properly map a JSON response into a state by excluding the first array and only displaying its children. Here is an example of what I have attempted: fetch(api).then((response) => { response.json().then((data) => { data.children. ...

The Angular Library seems to be malfunctioning as it does not execute the ngOnInit

I've been following the instructions from Angular CLI 6 to create a library, which can be found here. So far, I've successfully created and built my library. It includes a Component that I'm using for the UI and has an HTML selector. @Compo ...

AngularJS: Utilizing UI Bootstrap Popover with the Placement Set to 'bottom-right'

I am working with UI Bootstrap and AngularJS, attempting to customize a popover to have the 'bottom-right' placement instead of the default 'bottom' or 'right'. The desired functionality is illustrated in the image below. htt ...

Retrieving an Angular Application directly from the Server

In order to ensure user authentication from the backend before any other code loads in my Angular app, I need the initial request sent to the backend to check if the user is authenticated. Only once the user has been verified as authenticated can the app b ...

Keeping track of the toggle state using a cookie

While searching for a way to retain the toggle state, I stumbled upon js-cookie on GitHub. The documentation provides instructions on creating, reading, and deleting a cookie. However, an example would have been really helpful in enhancing my understanding ...

Creating a MySQL table that includes long string data types

Recently, I was working on creating an online forum and encountered a problem with the writing function. The form consists of a title and content section, which usually functions properly. However, when I enter a slightly longer text in the content field, ...

The colorbox popup is experiencing difficulty loading the Google Map from an inline div specifically in IE7

Using the following code, you can load a Google map from an inline div to a Colorbox popup window in all modern browsers. However, it may not work with outdated browsers like IE7. <head> <script src="http://maps.googleapis.com/maps/api/js?key=/// ...

What is the best way to create a function that triggers another function every minute?

Currently, I have a function that checks if a user is authenticated: isAuthenticated = (): boolean => { xxx }; I am working with AngularJS and I want to create a new function called keepCheckingAuthentication() This new function should call the ...

show information in a continuous manner using javascript

I'm having trouble extracting the latitude and longitude coordinates of markers to display them on the map. Even though my parser.php file successfully retrieves data from the database, I am struggling to format it into JavaScript. Any suggestions? & ...

There is an error in ReactJS: TypeError - _this.props.match is not defined

I am experiencing a TypeError in my console tab and I can't seem to figure out where the error is occurring in my source code. I am relatively new to ReactJS so any help in identifying what I'm doing wrong would be greatly appreciated. Thank you ...