gpt4 book ai didi

javascript - Promise.all() 每个 promise 响应

转载 作者:行者123 更新时间:2023-11-28 04:02:46 25 4
gpt4 key购买 nike

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

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

由于我需要等待所有 promise 都得到履行,直到进入下一步,我该如何正确地做到这一点?

最佳答案

您可以为每个 Promise 分配一个 resolveCallback。然后,使用 Promise.all() 等待所有 Promise 完成需要等待所有 Promise 完成的工作。

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)

关于javascript - Promise.all() 每个 promise 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46958322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com