From 0b6a7d88ab438414d87aa149d7c7eea509b43a23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Mazayev?= Date: Mon, 23 Oct 2023 13:29:53 +0100 Subject: [PATCH] Cancel pending transactions when calling destroy (#521) * add jsdocs * allow to pass more opts to socket * allow to pass AbortSignal to socket * add abort signal example * lint the code * remove vscode/ from gitignore * drop node v14 (reached EOL April 2023) * cancel pending transactions on destroy * remove comments --- index.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/index.js b/index.js index d0d3de5..5f95820 100644 --- a/index.js +++ b/index.js @@ -637,6 +637,20 @@ class ModbusRTU extends EventEmitter { return false; } + /** + * Clears the timeout for all pending transactions. + * This essentially cancels all pending requests. + */ + _cancelPendingTransactions() { + if (Object.keys(this._transactions).length > 0) { + Object.values(this._transactions).forEach((transaction) => { + if (transaction._timeoutHandle) { + _cancelTimeout(transaction._timeoutHandle); + } + }); + } + } + /** * Close the serial port * @@ -661,6 +675,9 @@ class ModbusRTU extends EventEmitter { * or failure. */ destroy(callback) { + // cancel all pending requests as we're closing the port + this._cancelPendingTransactions(); + // close the serial port if exist and it has a destroy function if (this._port && this._port.destroy) { this._port.removeAllListeners("data");