Promise.all()每个承诺响应

时间:2017-10-26 15:32:04

标签: javascript promise ionic3

我需要在循环中调用ascync操作:

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
  });

然后对于每个响应,我需要增加一个这样的计数器

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

我怎么能以正确的方式做到这一点,因为我需要等待所有的承诺被填满,直到进入下一步?

2 个答案:

答案 0 :(得分:1)

您可以为每个承诺分配resolveCallback。 然后,使用Promise.all()等待你所有的承诺,做任何需要等待所有这些工作完成的工作。

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)

答案 1 :(得分:-1)

Promise.all并行运行嵌套的promises。你不能使用反AFAIK。至少不要将计数器改为副作用。