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

Close not calling the callback #582

Open
hcraT opened this issue Feb 25, 2025 · 1 comment
Open

Close not calling the callback #582

hcraT opened this issue Feb 25, 2025 · 1 comment

Comments

@hcraT
Copy link

hcraT commented Feb 25, 2025

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.

@yaacov
Copy link
Owner

yaacov commented Feb 26, 2025

Thank you for the issue, can you make a pull request that fixes this issue ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants