16

I'm executing some asynchronous process with firebase with NodeJS.

I'd like to stop when finish all tasks the NodeJS process execution without the need of Ctrl+C command.

I tried to exit from the process, but it runs before all execution are done.

How can I do to run all asynchronous tasks and then exit from the script?

frankfullstack
  • 498
  • 5
  • 18

1 Answers1

24

First, all your asynchronous processes should be promises, then you wrap all of these promises in a single promise with Promise.all and exit when that promise resolves. Like this:

Promise.all([

 promiseForAsynchronousProcess1,
 promiseForAsynchronousProcess2,
 promiseForAsynchronousProcess3,
 ... and so on...

]).then(process.exit);
Lennholm
  • 7,205
  • 1
  • 21
  • 30
  • 2
    For anyone else that, like me, is not thinking 100% asyc yet.. I made a dumb mistake before this clued me in. then() needs a function (process.exit) not a value (process.exit(0)). The latter will run as soon as node rips through your promise creations and exit with extreme prejudice. – moodboom Mar 30 '22 at 14:14