简体   繁体   中英

Promise.all() each promise response

I need to call ascync operations in a loop:

for (var i = 0; i < message.destinatarios.length; i++) {
  messageList.push(this.sms.send(destinatario.numero_celular, string));
 // this will take a litle time to be executed
}

// Here I need something to be fired each time one of the promises in messageList is resolved

Promise.all(messageList)
  .then(res => {
     //that is executed when all the promises have been resolved 
  })
  .catch(err => {
     // that is executed when some of then fail
  });

Then for each response I need to increment a counter like this

console.log("processing " + counter++ + " of " + messageList.length);

How would I do that in correct way since I need to wait for all promises to be fufilled until moving to the next step?

You can assign a resolveCallback to each promise. Then, use Promise.all() to wait for all your promises to do whatever work that needs to wait for all of them to finish.

let counter = 0;
for (var i = 0; i < message.destinatarios.length; i++) {
  const prom = this.sms.send(destinatario.numero_celular, string);
  messageList.push(prom);
  prom.then(() => {
    //your logic for whatever you want to do for every time a promise is resolved
    console.log("processing " + ++counter + " of " + messageList.length); 
  })
}
Promise.all(messageList)

Promise.all runs nested promises in parallel. You can't use counter AFAIK. At least without changing counter as a side-effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM