【发布时间】: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 () => { await push(); await push(); Promise.resolve(); };我再次测试但结果没有改变。@madflow
标签: node.js promise async-await