When I try to run the following code the process exits (note the while (true) loop around the connection code):
const modbus = require('modbus-serial');
const ip = '127.0.0.1';
const port = 8502;
function delay(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
(async () => {
while (true) {
let client = new modbus();
try {
console.log('trying to connect');
await client.connectTCP(ip, {port});
console.log('connected');
} catch (e) {
console.log(`Error connecting: ${e}`)
}
await delay(1000);
try {
console.log('closing');
await client.close();
console.log('after call');
} catch (e) {
console.log(`Error while closing: ${e}`)
}
}
})();
This was not easy to figure out because it didn't produce any errors. However I found that the issue happens when you call the method as a Promise.
The Promise needs to have either resolve or reject method called in order for the execution to proceed. However when you run the code above the handleCallback method is run in the "close" event handler at this line of tcpport.js. This call gets executed before the await client.close() line is reached and is that call via the this._port.close(callback) call at this line of index.js that sets the this.callback. So the this.callback is never run.
If you change the line closing the client in the code above to client.close(() => {}) avoiding in this way the Promise the program behaves as expected.
I'm not sure what could be the best way to fix this. My guess is that the callback should be called in the close method of TCPPort. In this way the timing is completely dependent from the user code. However I'm not sure what could be the implications of doing this in the rest of the code.
Thank you.
When I try to run the following code the process exits (note the
while (true)loop around the connection code):This was not easy to figure out because it didn't produce any errors. However I found that the issue happens when you call the method as a Promise.
The Promise needs to have either
resolveorrejectmethod called in order for the execution to proceed. However when you run the code above thehandleCallbackmethod is run in the "close" event handler at this line oftcpport.js. This call gets executed before theawait client.close()line is reached and is that call via thethis._port.close(callback)call at this line ofindex.jsthat sets thethis.callback. So thethis.callbackis never run.If you change the line closing the client in the code above to
client.close(() => {})avoiding in this way the Promise the program behaves as expected.I'm not sure what could be the best way to fix this. My guess is that the callback should be called in the
closemethod of TCPPort. In this way the timing is completely dependent from the user code. However I'm not sure what could be the implications of doing this in the rest of the code.Thank you.