unordered output with MQTTjs library

Viewed 62

I have the following app

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);
        }

    });
}

the current output is that I have a series of update then publish then a list of an update then a list of publish

update
publish
update
publish
update
publish
....(x times)
update
update
update
publish
publish
publish

Is there a way to transform the output into update then publish for all iterations. I tried adding awaits in different part of the app but still no luck.

1 Answers

As the map function is asynchronous, the node main loop won't wait for the current iteration to finish to execute the next one.

This should work instead :

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();
});
Related