From 7db569872c1684a33e9f251b04097f170e96baaa Mon Sep 17 00:00:00 2001 From: Graziano Grespan Date: Fri, 16 Aug 2024 19:56:15 +0200 Subject: [PATCH] feat: Allow close method to be used with Promises or callbacks --- index.js | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index 04242ac..26ac6e1 100644 --- a/index.js +++ b/index.js @@ -669,16 +669,27 @@ class ModbusRTU extends EventEmitter { * * @param {Function} callback the function to call next on close success * or failure. - */ + */ close(callback) { - // close the serial port if exist - if (this._port) { - this._port.removeAllListeners("data"); - this._port.close(callback); - } else { - // nothing needed to be done - 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(); + } + }); } /**