Skip to content

Commit

Permalink
Merge pull request #21 from 123joshuawu/add-async-connect
Browse files Browse the repository at this point in the history
Add connectAsync
  • Loading branch information
RangerMauve committed Aug 7, 2019
2 parents fcc40b5 + f8ff21b commit b937299
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
42 changes: 42 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,5 +139,47 @@ module.exports = {

return asyncClient;
},
connectAsync (brokerURL, opts, allowRetries=true) {
const client = mqtt.connect(brokerURL, opts);
const asyncClient = new AsyncClient(client);

return new Promise((resolve, reject) => {
// Listeners added to client to trigger promise resolution
const promiseResolutionListeners = {
connect: (connack) => {
removePromiseResolutionListeners();
resolve(asyncClient); // Resolve on connect
},
end: () => {
removePromiseResolutionListeners();
resolve(asyncClient); // Resolve on end
},
error: (err) => {
removePromiseResolutionListeners();
client.end();
reject(err); // Reject on error
}
};

// If retries are not allowed, reject on close
if (allowRetries === false) {
promiseResolutionListeners.close = () => {
promiseResolutionListeners.error("Couldn't connect to server");
}
}

// Remove listeners added to client by this promise
const removePromiseResolutionListeners = () => {
Object.keys(promiseResolutionListeners).forEach((eventName) => {
client.off(eventName, promiseResolutionListeners[eventName]);
});
};

// Add listeners to client
Object.keys(promiseResolutionListeners).forEach((eventName) => {
client.on(eventName, promiseResolutionListeners[eventName]);
});
});
},
AsyncClient
};
14 changes: 14 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ function runTests () {
})
});

test('ConnectAsync should return AsyncClient after connection', t => {
t.plan(1);

AsyncMQTT.connectAsync(SERVER_URL, {}, false).then((client) => {
t.ok(client.connected, 'AsyncClient is connected');

client.end();
}, (error) => {
t.fail(error);
});


});

test('Should be able to listen on event on client', t => {
t.plan(1);

Expand Down

0 comments on commit b937299

Please sign in to comment.