gpt4 book ai didi

javascript - process.on ('uncaughtException' 的令人困惑的事件发射器/关闭模式)

转载 作者:行者123 更新时间:2023-12-03 07:37:38 25 4
gpt4 key购买 nike

好吧,这有点令人困惑,所以请留在此处

我有一个工作线程,它是 Node.js child_process,以 fork() 启动

工作进程从父进程接收消息,执行一些工作,然后在完成后发回消息。我的目标是将工作线程的所有代码都放在 process.on('message') 处理程序中,以便我可以使用 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
}

最佳答案

是的,它删除正确的监听器 - 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 ]

关于javascript - process.on ('uncaughtException' 的令人困惑的事件发射器/关闭模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35544456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com