Monday 5 June 2017

Wrap node.js process.on in promise not working as expected?

So, I've got this code in a child process:

function send(msg) {
  return new Promise((resolve, reject) => {
    process.send(msg);
    process.on('message', (recvd) => {
      return resolve(recvd);
    }
  });
}

And then invoke it like such:

const promises = largeArray.map(msg => send(msg))
Promise.all(promises)
  .then(results => {
    // here if you console, results.length == largeArray.length 
    process.exit(0);
  });

And on the parent side:

child.on('message', (msg) => {
  child.send('received');
  doSomething(msg);
});

And what's happening is the child process is exiting before all the messages have been sent. I suspect I'm confused here about node's ipc mechanism working asynchronously. Any help or direction would be appreciated. Thanks.



via R.A. Lucas

No comments:

Post a Comment