简体   繁体   English

在for循环中等待事件函数

[英]await a Event function inside a for loop

I need to wait inside a for loop untill a event function is called. 我需要在for循环内等待,直到调用了事件函数。 Im awaiting a response from a child process, that I'm creating with let worker = cluster.fork(); 我正在等待子进程的响应,我正在使用let worker = cluster.fork();创建let worker = cluster.fork(); I'm answering every child process with a special message within an array. 我正在用数组中的特殊消息回答每个子进程。 so if the for loop continues without waiting i might send it the wrong data ( the data of the next device or so on). 因此,如果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});
   }
}

So my question is how can i wait untill my worker.on() function is being called? 所以我的问题是我怎么能等到我的worker.on()函数被调用?

The worker.on function is being called sequentially and completes. worker.on函数被依次调用并完成。 There is nothing asynchronous about worker.on . 关于worker.on没有什么异步的。 However, it is registering a function to be called by some other means, presumably, when the worker submits a message back to the cluster. 但是,它正在注册要通过其他方式调用的功能,大概是在工作程序将消息提交回集群时。

Details aside, the worker.on function submits the anonymous function to be called at a later time. 除了细节之外, worker.on函数将提交匿名函数以供以后调用。 If the concern is that the data being passed to that anonymous function might be affected by the iteration, then I think your code seems fine. 如果担心的是传递给该匿名函数的数据可能会受到迭代的影响,那么我认为您的代码看起来不错。

There may be an issue with how you are declaring the worker variable because it is defined in the enclosed scope of the if conditional. 您如何声明worker变量可能存在问题,因为它是在if条件的封闭范围内定义的。 However, the code you are questioning should function like the below: 但是,您要查询的代码应具有以下功能:

 // 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 } }); }); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM