Continue iterating only when all promises have been resolved

My AngularJS requirement involves the following:

 for (var i = 0, len = self.Scope.data.length; i < len; i++) 
{

         var data = self.Scope.data[i];
         var self = this;
//Executing First asynchronous function
self.EcritureService.createNewData(data).then(() => {
         })                                                     
//Executing Second asynchronous function
self.OperationService.getOperation(data.idOperation).then((operation) => {

         })   
//Executing Third asynchronous function
self.AccountService.getAccount(data.codeCompte).then((compte) => {
               currentAccount = compte;
               currentAccount.montant = currentAccount.montant+data.montant;
         })   
//Executing Fourth function depending on the third result to execute sequentially
self.AccountService.updateAccount(currentAccount).then(() => {
         })                    
}
// Once all promises from the fetch loop are resolved, I need to proceed with additional steps to update the operation fetched in the second function

I require the loop iterator to wait until all promises are resolved before proceeding to the next step and ensuring that all tasks are completed before moving to the final functionality outside the loop block.

Answer №1

Generate arrays containing promises and utilize $q.all(promise_array) to execute when all promises are successfully resolved

// create an array of `$q.all()` promises
let promises = self.Scope.data.map((data) => {
  //First asynchronous function
  let promise_1 = self.EcritureService.createNewData(data).then(() => {})
  //Second asynchronous function
  let promise_2 = self.OperationService.getOperation(data.idOperation).then((operation) => {

  })
  //Third asynchronous function
  let promise_3 = self.AccountService.getAccount(data.codeCompte).then((compte) => {
    currentAccount = compte;
    currentAccount.montant = currentAccount.montant + data.montant;
    return currentAccount;
  }).then((currentAccount) => {
    //return promise of 4th inside `then()` of third
    return self.AccountService.updateAccount(currentAccount).then(() => {});
  });

  // this `$q.all()` resolves when this mapped instance of above all resolve
  return $q.all([promise_1, promise_2, promise_3]);

});

// resolves when all the loop instances of `$q.all()` resolve
$q.all(promises).then(()=>{
  // run completion code here
}).catch(err=>{
  console.log('Something failed in promise chain')
})

Answer №2

Initially, it's worth noting that transforming those services into promises may not be the ideal approach since you aim to avoid their inherent "promiseness." The most straightforward fix would involve revising the services to return values conventionally instead of via promises.

To address your inquiries, let's start with the latter part first. The simplest way to link the fourth promise to the third is by nesting it within the third .then block, as depicted below:

//Code for the third asynchronous function 
self.AccountService.getAccount(data.codeCompte).then((compte) => {
           currentAccount = compte;
           currentAccount.montant = currentAccount.montant+data.montant; 
           //The fourth function relies on the outcome of the third, so it should run sequentially
           self.AccountService.updateAccount(currentAccount).then(() => {
     })  
 })

If error handling is in place, you might consider placing the nested promise inside a .finally clause instead.

Regarding making the loop wait, standard for loops are not built for that purpose. To achieve this, you could create a custom loop and utilize $q.all to combine the promises. It would involve keeping track of a loop counter, incrementing it in the .then block of $q.all, and employing a recursive function that terminates once the necessary number of loops is completed.

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

Enhancing NodeJS performance when manipulating arrays

I'm seeking a way to retrieve a user's chat history with other users from a separate collection in NodeJS and MongoDB. I have concerns about the potential performance impact of running the code below due to the nature of NodeJS. While I could d ...

How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once. In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type. The goal is to deactivate al ...

Ways to retrieve an input field value without triggering form submission

I'm currently working on a payment form where users input the amount in a text field. I also have another text field on the same form that should automatically display the amount in words based on the user input. However, I'm struggling to figure ...

What could be causing the shake effect on the MUI dialog to not work when clicking away?

I am trying to implement a shake effect when the user clicks outside the MUI dialog to indicate that clicking away is not allowed. However, the code I have so far does not seem to be working as the effect is not being applied. Can someone please help me ...

Is it possible to retrieve a static resource within server-side code in NextJs?

Exploring the static render feature of NextJS to generate a static version of my website has led me to ensure that all necessary data is provided for the initial page render. I have stored several blog posts as .md files in /static and aim to access them ...

Leveraging the power of Google Charts along with MySQL or

I've been working on this task for several days now and I'm still struggling to achieve the desired outcome. My goal is to dynamically create a column/bar chart using Google Charts, populated with data from my database. Here's my query: SE ...

Setting up craco for jsx in your project

I am currently utilizing craco and grappling with how to configure jsx. I keep encountering the error below: Support for the experimental syntax 'jsx' isn't currently enabled (4:17): The suggestion is to add `babel/preset-react or utilize ...

JavaScript encountering a NaN value

I'm encountering an issue where I am receiving a NaN when attempting to summarize columns of a report. Additionally, my query is only retrieving 1 row of data, but the grid is displaying 2 rows. Does anyone have any suggestions on how to resolve this ...

Utilize a jQuery class selector to retrieve the value of a textbox through HTMLHelper

How can I retrieve the value of "StudentID" in a JavaScript function using jQuery? HTML: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Student.Models.vwStudent>>" %> <div class="divClass"> ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

Implementing a tooltip or bubble display functionality without using the span tag or title attribute

Is there a way to display tooltips when users hover over specific text or keywords? The text is retrieved directly from the database, so adding span or div tags or title information is not an option. Are there any methods to automatically generate tooltips ...

Node.js is facing a problem with its asynchronous functionality

As a newcomer to node, I decided to create a simple app with authentication. The data is being stored on a remote MongoDB server. My HTML form sends POST data to my server URL. Below is the route I set up: app.post('/auth', function(req, res){ ...

When calling a function within a for loop, the function receives the final value instead of iterating through the sequence

I need assistance with setting unique names for objects in an array. I have the following setup: this.array = [{name: null}, {name: null}, {name: null}] Along with a list of reserved names: this.reserved = ["name2", "name3"] My goal is to loop through th ...

Divide a string into smaller sections beginning at " ] " and concluding with "As"

In Microsoft SQL Server 2008 R2, I have fetched a string from a stored procedure using the query: EXEC sp_helptext 'MyStoredProcedureName';. My task is to divide this string into arrays or substrings that start from the closing parenthesis "]" a ...

Tips for validating email addresses and enforcing minimum length requirements

In order to validate email input for the correct format and ensure minimum length validations for first name and password, I am looking to utilize only bootstrap. While I have successfully implemented required field validations for the inputs, I am unsure ...

Angular promise fails to resolve after an extended period of waiting for a response

My application is designed to send GET requests to my node/express server. In order to monitor changes in the server code, I have implemented a setTimeout function. While the promise function on the client side initially functions properly for a short peri ...

Using React for form validation

I'm facing a challenge while trying to develop a user registration form, especially when it comes to displaying form validation errors. Issues: 1) The input fails to post (via axios) to the database upon submission for inputs without errors. 2) The e ...

Animate the React Bootstrap modal only when it is shown or hidden

I am experimenting with the idea of transitioning smoothly from one modal to another in bootstrap Modals for react (using react-bootstrap). However, I am facing challenges due to the fade CSS class causing flickers and unwanted animations. My goal is to h ...

What is preventing me from accessing my session array in this.state.props from my mapStateToProps in React-Native Redux?

I am currently facing an issue with my Redux store setup. I am attempting to store an array of Session objects, where each Session object contains an array of Hand objects. However, when trying to access my store using `mapStateToProps`, none of the option ...

Is it possible to achieve a smooth transition to the right using CSS

I'm attempting to create a sliding box effect from left to right using only transitions, similar to this: #box { width: 150px; height: 150px; background: red; position:absolute; transition: all 2s ease-out; right:auto; } .active{ bac ...