【问题标题】:Nodejs: execute then from Promise.all immediatalyNodejs:然后从 Promise.all 立即执行
【发布时间】:2019-09-29 21:54:56
【问题描述】:

如您所见,我创建了一个异步方法列表。在 for 循环中的异步方法内部,我将 mqtt 客户端的一些消息推送到代理:

const example2 = async () => {
    await push();
    await push();
};
const push = async () => {
    for (var i = 0; i < 2000; i++) {
        client.publish(topic, message, pushOptions);
    }
}
var syncList = [];
const startpushing = () => {
    if (client.connected & client2.connected & client3.connected & client4.connected & client5.connected) {
        console.log(`start pushing`);
        syncList.push(
            example2(), example3(), example4(),...);
        Promise.all(syncList)
            .then(() => {
                console.log(topic_finished);
                client5.publish(topic_finished, "true", pushOptions);
            }).catch(err => {
                console.log(err);
            });
    }
}

我想在执行所有异步方法后将新主题推送到代理,所以我使用了Promise.all

但是我不知道为什么console.log(topic_finished)在我的任务列表还没有完成的时候很快就执行了?

我认为这是因为 我没有从我的 async 方法返回任何内容?正确的?但是我应该返回什么?

【问题讨论】:

  • 您的push 函数实际上是同步的,因此它会立即解析
  • > 但是我应该返回什么?你应该返回一个 Promise(解决/拒绝)。
  • 好的,但是在哪里?在 client.publish 或 example2 中? @madflow
  • Promise.all 期望一个可迭代的 Promise。良好的起点。
  • 我将我的方法更改为:const example2 = async () =&gt; { await push(); await push(); Promise.resolve(); }; 我再次测试但结果没有改变。@madflow

标签: node.js promise async-await


【解决方案1】:

你应该在不调用的情况下推送 fns

syncList.push(example2, example2, ...anotherAsyncFns)

然后添加参数

Promise.all(syncList).then((results) => console.log(results));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 2016-07-22
    • 2016-03-19
    相关资源
    最近更新 更多