gpt4 book ai didi

node.js - MQTTjs 库的无序输出

转载 作者:行者123 更新时间:2023-12-04 09:59:14 26 4
gpt4 key购买 nike

我有以下应用程序

const RSVP = require('rsvp');
const Mqtt = require('mqtt');
let client = Mqtt.connect("alis://test.mosquitto.org");
let dataPoints = [{ "id": 1, "message": "message-1" }, { "id": 2, "message": "message-2" }, { "id": 3, "message": "message-3" },
{ "id": 4, "message": "message-4" }, { "id": 5, "message": "message-5" }, { "id": 6, "message": "message-6" }
];

client.on('connect', async () => {
main();
});
function main(){
for(var i=0;i<200;i++) {
dataPoints.map(async (dataPoint) => {
console.log("update");
await publish("message", "key");
});
}
}

function publish(topic, payload) {
return new RSVP.Promise((resolve, reject) => {
try {
client.publish(topic,
payload,
(error) => {
if (error) {
reject(error);
} else {
console.log("publish")
resolve();
}
});
} catch (error) {
console.log(error);
}

});
}

当前的输出是我有一系列更新然后发布然后更新列表然后发布列表
update
publish
update
publish
update
publish
....(x times)
update
update
update
publish
publish
publish

有没有办法将输出转换为更新然后发布所有迭代。我尝试在应用程序的不同部分添加等待,但仍然没有运气。

最佳答案

map函数是异步的, Node 主循环不会等待当前迭代完成执行下一个。

这应该起作用:

const client = Mqtt.connect('alis://test.mosquitto.org');
const dataPoints = [
{ id: 1, message: 'message-1' },
{ id: 2, message: 'message-2' },
{ id: 3, message: 'message-3' },
{ id: 4, message: 'message-4' },
{ id: 5, message: 'message-5' },
{ id: 6, message: 'message-6' }
];

async function main() {
for (let i = 0; i < 200; i++) {
for (const dataPoint in dataPoints) {
console.log('update');
await publish('message', dataPoint.message);
}
}
}

function publish(topic, payload) {
return new RSVP.Promise((resolve, reject) => {
try {
client.publish(topic, payload, error => {
if (error) {
reject(error);
} else {
console.log('publish');
resolve();
}
});
} catch (error) {
console.log(error);
}
});
}

client.on('connect', async () => {
await main();
});

关于node.js - MQTTjs 库的无序输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61867244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com