最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

Nodejs:然后从Promise.all立即执行

IT培训 admin 3浏览 0评论

Nodejs:然后从Promise.all立即执行

您可以看到我已经创建了异步方法列表。在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方法中的[[我什么都不返回?对?但是我应该返回什么?

回答如下:您应该在不调用fns的情况下推动fns

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

然后在其中添加参数

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

Nodejs:然后从Promise.all立即执行

您可以看到我已经创建了异步方法列表。在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方法中的[[我什么都不返回?对?但是我应该返回什么?

回答如下:您应该在不调用fns的情况下推动fns

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

然后在其中添加参数

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

发布评论

评论列表 (0)

  1. 暂无评论