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

Cancel pending transactions when calling destroy #521

Merged
merged 10 commits into from
Oct 23, 2023
20 changes: 20 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,23 @@ 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);
}
});
}
}

// eslint command to fix this file
// eslint --fix index.js
yaacov marked this conversation as resolved.
Show resolved Hide resolved

/**
* Close the serial port
*
Expand All @@ -661,6 +678,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");
Expand Down