好的,这有点令人困惑所以请留在这里
我有一个工作人员,这是以child_process
fork()
工作人员从父进程接收消息,执行某些操作,然后在完成后发回消息。我的目标是在process.on('message')
处理程序中为worker提供所有代码,以便我可以在JS中使用闭包的强大功能。但是,我的问题是,当处理消息/数据时,我想删除监听器onUncaughtException
函数。但这只会删除正确的函数吗?
const assert = require('assert');
process.on('message', function (data) {
var workId = data.workId;
assert(workId); //workId is an integer greater than 0
process.on('uncaughtException', onUncaughtException);
function onUncaughtException(err) {
process.removeListener('uncaughtException', onUncaughtException); //<< this removes the listener, but will it remove only the correct function?
process.send({
msg: 'fatal',
error: err.stack,
workId: workId
});
}
//some more functions exist done here to do work, but I omit them for clarity's sake
}
答案 0 :(得分:1)
是的,它会删除correct listener
- emitter.removeListener(event, listener)
通过引用删除侦听器:
<强> index.js 强>
var f = require('child_process').fork( './worker.js' );
f.send(0);
f.send(2);
f.send(11);
f.send(8);
f.send(11);
f.send(10);
f.send(11);
<强> worker.js 强>
process.on('message', function (index) {
function listener() {
return index;
}
process.on('listen', listener);
if (index>10) {
process.removeListener('listen', listener);
var index = process.listeners('listen').map( function(f) {
return f();
});
console.log( index );
}
});
<强>输出强>
[ 0, 2 ]
[ 0, 2, 8 ]
[ 0, 2, 8, 10 ]