【问题标题】:waiting for two promises with events and loop等待两个带有事件和循环的承诺
【发布时间】:2021-07-02 04:20:06
【问题描述】:

我有一段这样的代码:

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

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

【问题讨论】:

  • 你不能同时运行两个循环

标签: javascript node.js loops events child-process


【解决方案1】:

将它们放在使用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();

【讨论】:

    【解决方案2】:

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

    让 arrayRequests = [ forkedChildOne.on('消息'), forkedChildTwo.on('message') ];

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

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

    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 2022-12-08
      • 2017-12-16
      • 2020-05-15
      • 2015-11-13
      • 2016-04-13
      • 1970-01-01
      相关资源
      最近更新 更多