Using Node.js, how to wait for all spawn processes to be completed

Viewed 22

I use node.js 18.9.1 on Windows.

I have a list of files (array) and need to process externally, in parallel, with a executable. After ALL processes completed, if ALL succeeded I need to go further.

Using spawn, seems that all executes in parallel (I see this in their PID) which is good.

But I just can't figure out how to wait blocking until ALL finishes and if possible, collect their result codes (to see success/error).

const promises =  MyFilesArray.map(async iFile => {

    const res = spawn(myExe, iFile);

    res.on("close", code => {
        console.log(`child process exited with code ${code}`);
    });

    return res;
});

async function main() {
    const response = await Promise.all(promises);
    console.log(response);
  }
  
  main();

  console.log('done'); // this needs to be executed AFTER all async processes that run in parallel, completes !

Thanks for any hints in advance!

1 Answers

You need to create promises that will resolve when each process have finished. You just created a promise with async callbacks but that's not gonna have the effect you want since the promises will resolve inmediately.

const successCode = /* whatever code means success */

// Map the files array to a map of promises
// which will resolve when each process have finished
const processPromises = MyFilesArray.map(iFile => {
  const res = spawn(myExe, iFile);

  return new Promise((resolve, reject) => {
    res.on("close", code => {
      if (code === successCode) {
        resolve(code)
      } else {
        reject(code)
      }
    });
  });
});

async function main() {
  const response = await Promise.all(processPromises);
  console.log(response);
}
  
main();
Related