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\n');
return allPromises;
};
(async () => {
const promisesArray = getPromiseArray();
await Promise.all(promisesArray);
})();
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\n');
return allPromises;
};
(async () => {
const promisesArray = getPromiseArray();
await Promise.all(promisesArray);
})();