async-mqtt
Promise wrapper over MQTT.js
IMPORTANT: Make sure you handle rejections from returned promises because they won't crash the process
API
The API is the same as MQTT.js, except the following functions now return promises instead of taking callbacks
- publish
- subscribe
- unsubscribe
- end
Example
const MQTT = require("async-mqtt");
const client = MQTT.connect("tcp://somehost.com:1883");
const doStuff = async () => {
console.log("Starting");
try {
await client.publish("wow/so/cool", "It works!");
await client.end();
console.log("Done");
} catch (e){
console.log(e.stack);
process.exit();
}
}
client.on("connect", doStuff);
Alternately you can skip the event listeners and get a promise.
const MQTT = require("async-mqtt");
run()
async function run() {
const client = await MQTT.connectAsync("tcp://somehost.com:1883")
console.log("Starting");
try {
await client.publish("wow/so/cool", "It works!");
await client.end();
console.log("Done");
} catch (e){
console.log(e.stack);
process.exit();
}
}
Wrapping existing client
const { AsyncClient } = require("async-mqtt");
const client = getRegularMQTTClientFromSomewhere();
const asyncClient = new AsyncClient(client);
asyncClient.publish("foo/bar", "baz").then(() => {
console.log("We async now");
return asyncClient.end();
});