node.js - MQTTjs 库的无序输出

标签 node.js asynchronous async-await mqtt

我有以下应用

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/

相关文章:

javascript - 如何在 npm 脚本中加载外部文件?

html - 使用 Node、Express 和 EJS 压缩 HTML?

jquery - "Typeahead is not a function"错误

javascript - API 返回数据,但在 undefined object 中。这是怎么回事?

c# - 如何同时构建字符串?

javascript - NodeJS 异步函数与 mongoose

javascript - Node.js 和客户端共享相同的脚本

java - JRedis future 稳定

javascript - 一旦父 http 请求中的所有子 http 请求完成,我如何返回

c# - 在 C# 中使用 await 内部属性