等待所有子进程完成以继续

时间:2019-04-11 22:50:27

标签: node.js asynchronous child-process

我想知道在继续执行之前是否可以等待使用spawn函数创建的所有子进程完成。

我有一个看起来像这样的代码:


    const spawn = window.require('child_process').spawn;

    let processes = [];
    let thing = [];
    // paths.length = 2
    paths.forEach((path) => {
        const pythonProcess = spawn("public/savefile.py", ['-d', '-j', '-p', path, tempfile]);

        pythonProcess.on('exit', () => {
            fs.readFile(tempfile, 'utf8', (err, data) => {
                thing.push(...)
            });
        });

        processes.push(pythonProcess);
    });

    console.log(processes) // Here we have 2 child processes
    console.log(thing) // empty array.. the python processes didnt finish yet

    return thing // of course it doesn't work. I want to wait for all the processes  to have finished their callbacks to continue

您可能会猜到,我想知道如何使所有python脚本同时运行,并等待它们全部完成以继续我的js代码。

我正在运行节点10.15.3

谢谢

1 个答案:

答案 0 :(得分:0)

ForEach将Promise推入Promise和Promise.all()数组