josdejong / workerpool

Offload tasks to a pool of workers on node.js and in the browser
Apache License 2.0
2.06k stars 147 forks source link

adds worker-side on(message) events #372

Open flipswitchingmonkey opened 1 year ago

flipswitchingmonkey commented 1 year ago

This PR is related to https://github.com/josdejong/workerpool/issues/370

A rather small change that adds a second parameter to workerpool.worker() function, which accepts an object where each key is the receiver's name of an event, plus a payload.

It also adds an emit() function to the Promise object which will send a postMessage() call to the worker instance.

These changes should be non-breaking.

Example: workers/myworker.js

workerpool.worker({
  fibonacci: fibonacci,
}, {
  callme: function (payload) {
    makeThingsHappen(payload);
  }
});

And to call the event:

const pool = new Pool(__dirname + "/workers/myworker.js");

// main difference here is that the handler, a Promise, is picked up from the exec() command first
const handler = pool.exec('fibonacci', [15]);

// now continue the chaining
handler
  .then(function (result) {
    assert.strictEqual(result, 610);
  })
  .catch(function (err) {
  })
  .then(function () {
    pool.terminate(); // terminate all workers when done
  })

// the Promise now has a function Promise.emit(name, paramerers) 
handler.emit('callme', {say: 'O hai!'});
blordpluto commented 3 months ago

The functionality here is crucial for my team to use this package. This PR appears to have been abandoned, and now unsurprisingly conflicts greatly. @josdejong what would be your level of interest in re-approaching this?

josdejong commented 3 months ago

@blordpluto thanks for your input. I would love to see this feature finished. The PR was under review but not yet there. Would you be interested in creating a new PR implementing this feature?