Angular 8 - How to properly await a promise's completion within a loop before moving on to the

I have a list that needs to be iterated through, with each iteration dependent on the completion of the previous one. Each iteration returns a promise.

Currently, my code processes the list quickly without waiting for the promises to resolve:

this.records.forEach(item => {
  this.myService.doFirstTask().then(res => {
    if (res) {
      this.myService.doSecondTask().then(res => {
        if (res) {
          // do something.
        }
      });
    }
  });
});

The issue is that I need to wait for myService.doSecondTask() to finish before moving to the next item in the list.

I understand that using an async function with await could solve this problem, but I'm unfamiliar with it.

Could someone please offer guidance on how to wait for a nested promise to resolve before iterating through the .forEach loop?

Should I use async-await in the .doSecondTask() function as the solution?

Answer №1

Since you are working in Angular, utilizing observables is recommended. If your service returns observables instead of promises as it should in Angular, you can utilize RxJs concatMap.

from(this.records).pipe(
  concatMap(record => this.myService.doFirstTask(record)),
  switchMap(resultOfDoFirstTask => this.myService.doSecondTask())
).subscribe(resultOfDoSecondTask => {
  // Executes once for each record
});

This method using RxJs is preferred over promises in Angular because of its integration with RxJs.

Here is a sample snippet to demonstrate the implementation.

const { of, from } = rxjs;
const { concatMap, switchMap, delay } = rxjs.operators;

const records = [1,2,3,4,5,6];

const myService = {
  doFirstTask: val => of(`${val}: from first task`).pipe(delay(500)),
  doSecondTask: val => of(`${val}: from second task`).pipe(delay(500)),
};

from(records).pipe(
  concatMap(record => myService.doFirstTask(record).pipe(
    switchMap(resultOfDoFirstTask => myService.doSecondTask(resultOfDoFirstTask))
  ))
).subscribe(resultOfDoSecondTask => {
  console.log(resultOfDoSecondTask);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.0/rxjs.umd.min.js"></script>

If you prefer not to update your services to return observables, you can wrap them in a from function to convert them into an observable from a promise.

from(this.myService.doSecondTask())

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

Angular Bootstrap Datepicker provides us with a date object, but I need it in the Date format

My desired date format is "Wed Aug 07 2019 16:42:07 GMT+0530 (India Standard Time)", but instead I am receiving { year: 1789, month: 7, day: 14 } from ngbDatepicker. Any assistance on resolving this issue would be greatly appreciated. ...

The Angular service not only stores data but also handles HTTP requests internally

Instead of returning an observable to the requesting components and managing the data, I am considering using Angular services to handle HTTP requests autonomously. The goal is to have components retrieve data directly from the service where it is stored. ...

Is it considered valid in JavaScript or TypeScript to group values using (value1 || value2) for comparisons, and if it is, what is the reasoning behind

Does anyone know if using the || operator to group values while comparing a single variable is valid in the most recent versions of JavaScript or TypeScript? If not, what could be preventing this from becoming a valid syntactic sugar feature at some point? ...

Issue detected in rxjs-compat operator's shareReplay file at line 2, column 10:

I've encountered an issue with the angular material spinner I'm using in my project. The error message is as follows: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): error TS2305: Module '"D:/ControlCenter/ofservices ...

Exploring novel methods for managing CRUD components in Angular 2

Currently in the process of developing a set of CRUD components using Angular 2, I have noticed that most online examples include the Http service directly within the components. This means that the component responsible for creating a resource (referred t ...

Angular: Validation triggered following ngModelChange event

I am dealing with an input field that has a customValidator called fooValidator. This custom validator checks if the input matches a specific regular expression: <form #contratForm="ngForm"> <input type="text" ...

Is there a way for me to change the value and placeholder attributes on the Clerk's SignIn component?

Within Clerk's documentation, there is guidance on accessing the input field using the appearance prop as demonstrated below: <SignIn appearance={{ elements: { formFieldInput: 'bg-zinc-300/30' } }}/& ...

Formik QR code reader button that triggers its own submission

I recently developed a custom QR code reader feature as a button within the Formik component customTextInput.tsx, but I encountered an issue where clicking on the button would trigger a submission without any value present. The following code snippet show ...

RXJS Subject data remains stale upon page refresh

A specific service I developed includes a subject titled selectedNode. My goal is to update the subject's value when providing a direct URL for page loading. Unfortunately, there seems to be an issue with updating the value of Subject directly via the ...

Obtain the query response time/duration using react-query

Currently utilizing the useQuery function from react-query. I am interested in determining the duration between when the query was initiated and when it successfully completed. I have been unable to identify this information using the return type or para ...

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

Change the router outlet to the currently selected tab

We are in the process of conceptualizing a cutting-edge angular 7 application featuring material design (md-tabs) with multiple tabs. Our goal is to enable dynamic tab creation, with each tab representing the content of a specific route. The home page sh ...

Utilizing an API to dynamically augment a JSON object with user input in Angular

Hello, I am working on adding an input value to an object property. The scenario is that a customer wants to add an item to their shopping cart, but before adding the item, they need to choose the size. I have the form set up with validation and can retri ...

Transforming the unmanaged value state of Select into a controlled one by altering the component

I am currently working on creating an edit form to update data from a database based on its ID. Here is the code snippet I have been using: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material ...

The Nest.js Inject decorator is not compatible with property-based injection

I am facing an issue with injecting a dependency into an exception filter. Here is the dependency in question: @Injectable() export class CustomService { constructor() {} async performAction() { console.log('Custom service action executed ...

Remove a npm package from an angular application

When I run the following command on the command line and on gitBash: npm -g uninstall angualar2piwik --save I receive the following message: up to date in 0.16s The entry is not removed from package.json, nor are the node_modules removed. I have also ...

Transitive dependency in Npm that is not up to date

In our current Angular project, we are dealing with a transitive dependency as shown below: "dependencies": { ... "angular-fancybox-plus": "^1.0.3", This dependency results in the following dependency tree (with the latest version of angular-fa ...

Navigation problem in Angular: Page remains unchanged despite URL updating

I am experiencing an issue with two components, home and welcome. The welcome component contains a button that, when clicked, is supposed to take me to the 'home' page. However, instead of navigating to the home page and displaying its content, i ...

Angular2 is designed to break down complex applications into smaller, more manageable parts

Need for a Solution Recently, I was given responsibility of overseeing a large, legacy web application at work that involves multiple scrum teams and development teams. One major issue we face with this application is that whenever one team makes updates ...

It takes two clicks for the text to change on the button in Angular

As a newcomer to angular, I am working on a quiz application where I've encountered an issue. When I click a button, it requires two clicks to function properly. The first click works fine, but subsequent clicks on the next and back buttons need to be ...