等待事件和循环的两个承诺

waiting for two promises with events and loop

我有一段代码是这样的:

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

但是在这里,它首先等待第一个循环完成,然后进入第二个循环。但我需要 运行 它们并行。我怎样才能做到这一点?谢谢。

将它们放在使用 async 关键字定义的单独函数中。然后调用两个函数,一个接一个。

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

你可以尝试使用 Promise.all 吗?请尝试以下代码。我还没有测试过,但我相信它应该可以工作。

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

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

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

});