Search code examples
javascriptnode.jsloopseventschild-process

waiting for two promises with events and loop


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.


Solution

  • 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();