Skip to content

Commit

Permalink
feat: Allow close method to be used with Promises or callbacks (#562)
Browse files Browse the repository at this point in the history
* feat: Allow close method to be used with Promises or callbacks

* fix: refactor_convert fn to handle both single and multiple args cases

---------

Co-authored-by: Graziano Grespan <[email protected]>
  • Loading branch information
grazianogrespan and Graziano Grespan authored Aug 18, 2024
1 parent 629d76f commit 6649806
Showing 1 changed file with 26 additions and 13 deletions.
39 changes: 26 additions & 13 deletions apis/promise.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,28 @@
* @private
*/
const _convert = function(f) {
const converted = function(address, arg, next) {
const converted = function(...args) {
const client = this;
const id = this._unitID;

/* the function check for a callback
* if we have a callback, use it
* o/w build a promise.
*/
if (next) {
// if we have a callback, use the callback
f.bind(client)(id, address, arg, next);
// The last argument might be the callback (next)
const next = args[args.length - 1];

// Determine if the last argument is actually a callback
const hasCallback = typeof next === "function";

if (hasCallback) {
// If there is a callback, call the function with the appropriate arguments
if (args.length === 1) {
// This case is used for client close method
f.bind(client)(next);
} else {
// This case is used for client writeFC methods
f.bind(client)(id, ...args);
}
} else {
// o/w use a promise
const promise = new Promise(function(resolve, reject) {
// Otherwise, use a promise
return new Promise(function(resolve, reject) {
function cb(err, data) {
if (err) {
reject(err);
Expand All @@ -45,10 +53,14 @@ const _convert = function(f) {
}
}

f.bind(client)(id, address, arg, cb);
if (args.length === 0) {
// This case is used for client close method
f.bind(client)(cb);
} else {
// This case is used for client writeFC methods
f.bind(client)(id, ...args, cb);
}
});

return promise;
}
};

Expand All @@ -73,6 +85,7 @@ const addPromiseAPI = function(Modbus) {
cl.getTimeout = function() {return this._timeout;};

// convert functions to return promises
cl.close = _convert(cl.close);
cl.readCoils = _convert(cl.writeFC1);
cl.readDiscreteInputs = _convert(cl.writeFC2);
cl.readHoldingRegisters = _convert(cl.writeFC3);
Expand Down

0 comments on commit 6649806

Please sign in to comment.