David
David

Reputation: 1174

await a Event function inside a for loop

I need to wait inside a for loop untill a event function is called. Im awaiting a response from a child process, that I'm creating with 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(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?

Upvotes: 1

Views: 88

Answers (1)

Tim Klein
Tim Klein

Reputation: 2758

The worker.on function is being called sequentially and completes. There is nothing asynchronous about 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. 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. 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
            }
        });
    });
}

Upvotes: 2

Related Questions