javascript - 在 for 循环中等待事件函数
问题描述
我需要在 for 循环中等待,直到调用事件函数。我正在等待来自子进程的响应,我正在创建它let worker = cluster.fork();
我正在用数组中的特殊消息回答每个子进程。因此,如果 for 循环继续而不等待,我可能会向其发送错误的数据(下一个设备的数据等)。
for(var i=0;i<data.length;i++) {
if(connected_devices.includes(data[i].deviceID) == false) {
let worker = cluster.fork();
connected_devices.push(data[i].deviceID);
}
await worker.on('message', function (msg) { // wait untill this function is called then continue for loop
worker.send({ device: data[i].deviceID, data[i].name});
}
}
所以我的问题是我怎么能等到我的worker.on()
函数被调用?
解决方案
该worker.on
函数被顺序调用并完成。没有什么异步的worker.on
。但是,它正在注册一个要通过其他方式调用的函数,大概是当 worker 将消息提交回集群时。
抛开细节不谈,该worker.on
函数提交匿名函数以供稍后调用。如果担心传递给该匿名函数的数据可能会受到迭代的影响,那么我认为您的代码看起来不错。
您如何声明worker
变量可能存在问题,因为它是在条件的封闭范围内定义的if
。但是,您所质疑的代码应如下所示:
// Stubs for woker.on and worker.send
const stubWorker = {
on: (type, func) => {
console.log('worker.on called');
setTimeout(func, 1000);
},
send: (obj) => {
console.log(`Object received: ${JSON.stringify(obj)}`);
}
};
const cluster = {
fork: () => stubWorker
};
const data = [
{ deviceId: 0, name: 'Device Zero' },
{ deviceId: 1, name: 'Device One' },
{ deviceId: 2, name: 'Device Two' },
{ deviceId: 3, name: 'Device Three' }
];
for (let i = 0; i < data.length; ++i) {
// Removed if condition for clarity
const worker = cluster.fork();
worker.on('message', function () {
worker.send({
device: {
id: data[i].deviceId,
name: data[i].name
}
});
});
}