I'm currently using a child process in order to run some computational functions in a non-blocking way.
I'm running into an issue, where by I need to be able to tie the result of a computation back to the correct callback in the parent process. For example:
var cp = require('child_process');
var n = cp.fork(__dirname + '/child.js');
exports.evaluate = function(data, callback) {
n.send({ data : data});
n.once('message', function(result) {
callback(result);
}
}
The problem with this is example is that if one computation returns before another then it will not receive the correct results.
Is there any way to use a custom event name instead of 'message' in order to ensure that each time the evaluate function is called it creates a unique listener that will be removed once it is called?
How can I emit a custom event from with a child process?
Create a a new EventEmitter with new events.EventEmitter. Then emit an event based on any message with eventType:"someType" you receive.
i.e. something like
events = require("events")
emitter = new events.EventEmitter
n.on("message", function(msg) { emitter.emit(msg.eventType,msg.body) })
Then bind listeners (with once or on) to that event emitter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With