我对promise.all感到非常困惑,我有一堆这样的方法:
const push = async () => {
for (var i = 0; i < 2000; i++) {
return new Promise(invoke => {
client.publish(topic, message, pushOptions); // is mqtt client
invoke(true);
});
}
};
const example2 = async () => {
console.log('example2 started');
await push();
await push();
await push();
await push();
await push();
}; ....
现在我想通过承诺所有方法运行所有方法:
var syncList = [];
syncList.push(
example2, example3, example4);
Promise.all(syncList)
.then((result) => {
console.log(result);
}).catch(err => {
console.log(err);
});
但是没有方法启动,我在终端上得到了这个登录:
[ [AsyncFunction: example2],
[AsyncFunction: example3],
[AsyncFunction: example4] ]
为什么我的方法没有运行?
你的问题是,你立即return
你的第一个承诺。您的push
函数只返回一个承诺。
在下面的示例中,我们有一个返回未解析承诺数组的函数。可以与Promise.all()
一起等待
const getPromiseArray = () => {
console.log('start collecting tasks');
const allPromises = [];
for (var i = 0; i < 10; i++) {
const newTask = new Promise(function(invoke) {
const taskNr = i;
setTimeout(() => { // some long operation
console.log("task " + taskNr);
invoke();
}, 400);
});
allPromises.push(newTask);
}
console.log('end collecting tasksn');
return allPromises;
};
(async () => {
const promisesArray = getPromiseArray();
await Promise.all(promisesArray);
})();
Promise.all
得到一个Promise
数组,但你传递给它的不是Promise
s,而是一些异步函数声明。 当您将这些函数传递给Promise.all
时,您应该运行它们。
相当于这个的东西:
Promise.all([example2(), example3(), example4()])
当然,你的push
函数似乎也是错误的! 它的循环只运行i=0
因为它在循环迭代其他i
值之前返回。