Nodejs:Promise.all没有调用我的任何异步方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nodejs:Promise.all没有调用我的任何异步方法相关的知识,希望对你有一定的参考价值。
我对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
您的[[first承诺。您的push
函数仅返回一个Promise。
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 tasks
');
return allPromises;
};
(async () => {
const promisesArray = getPromiseArray();
await Promise.all(promisesArray);
})();
Promise.all
获得一个由Promise
组成的数组,但传递给它的不是Promise
,而是一些异步函数声明。将它们传递给Promise.all
时应运行这些函数。等同于此的内容:
Promise.all([example2(), example3(), example4()])
以上是关于Nodejs:Promise.all没有调用我的任何异步方法的主要内容,如果未能解决你的问题,请参考以下文章
在 node js 中使用 promise.all 进行外部 api 调用
为啥我的 apolloFetch 调用在从 promise.all 中调用时返回一个空查询?
在 forEach 之后使用 Promise.all() 渲染 NodeJS 页面之前等待 Firebase 数据加载
为啥在 Promise.all() 之后不调用 onRejected,其中包含在数组中的 Promise.reject() 传递给 Promise.all()?