最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Nodejs:Promise.all没有调用我的任何异步方法

运维笔记admin11浏览0评论

Nodejs:Promise.all没有调用我的任何异步方法

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

发布评论

评论列表(0)

  1. 暂无评论