diff --git a/apis/promise.js b/apis/promise.js index 8c7c985..e6dd82b 100644 --- a/apis/promise.js +++ b/apis/promise.js @@ -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); @@ -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; } }; @@ -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); diff --git a/index.js b/index.js index 26ac6e1..04242ac 100644 --- a/index.js +++ b/index.js @@ -669,27 +669,16 @@ class ModbusRTU extends EventEmitter { * * @param {Function} callback the function to call next on close success * or failure. - */ + */ close(callback) { - return new Promise((resolve, reject) => { - const cb = (err) => { - if (callback) { - callback(err); - } - if (err) { - reject(err); - } else { - resolve(); - } - }; - - if (this._port) { - this._port.removeAllListeners("data"); - this._port.close(cb); - } else { - cb(); - } - }); + // close the serial port if exist + if (this._port) { + this._port.removeAllListeners("data"); + this._port.close(callback); + } else { + // nothing needed to be done + callback(); + } } /**