Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow close method to be used with Promises or callbacks #562

Merged
merged 2 commits into from
Aug 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading