yhu420
yhu420

Reputation: 617

Wait for all child processes to finish to continue

I would like to know if it is possible to wait for all child process created using the spawn function to finish before continuing execution.

I have a code looking like this:


    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

As you can guess, I would like to know how I could get all the python scripts running at the same time, and wait for all of them to finish to continue my js code.

I'm running node 10.15.3

Thank you

Upvotes: 2

Views: 2597

Answers (2)

Giacomo A.
Giacomo A.

Reputation: 175

Have you tried spawnSync ?

Is generally identical to spawn with the exception that the function will not return until the child process has fully closed.

import { spawnSync } from "child_process";
spawnSync('ls', ['-la']);

Upvotes: 0

郑旭阳
郑旭阳

Reputation: 91

ForEach to push Promise into an array of Promise and Promise.all()

Upvotes: 1

Related Questions