0

i have a piece of code like this:

for(let j = 0; j < someNumber; j++) {
    const forkedChildOne = fork("./child.js");
    const childOne = await new Promise((resolve, reject) => {
        forkedChildOne.on('message', (msg){
            // someCode
            resolve(msg);
        });
    });
}

for(let i = 0; i < someAnotherNumber; i++) {
    const forkedChildTwo = fork("./child_numberTwo.js");
    const childTwo = await new Promise((resolve, reject) => {
        forkedChildTwo.on('message', (msg){
            // someCode
            resolve(msg);
        });
    });
}

but here, first it wait for the first loop to complete then it goes to the second loop. but i need to run them in parallel. how can i do that? thanks.

2 Answers2

1

Put them in separate functions defined with the async keyword. Then call both functions, one after the other.

const forkloop = async (number, js) {
    for(let j = 0; j < number; j++) {
        const forked = fork(js);
        const child = await new Promise((resolve, reject) => {
            forked.on('message', (msg){
                // someCode
                resolve(msg);
            });
        });
    }
}

const init = async () => {
    /* Do not await here */ forkloop(someNumber, './child.js');
    /* Do not await here */ forkloop(someAnotherNumber, './child_numberTwo.js');

}

init();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Can you please try using Promise.all ? Please try below code. I have not tested it,, but I believe it should work.

let arrayRequests = [ forkedChildOne.on('message'), forkedChildTwo.on('message') ];

return Promise.all(arrayRequests).then(results => {

let resultForkedChildOne = results[0];
let resultForkedChildTwo = results[1]; 

});

Satwinder Singh
  • 229
  • 2
  • 9