Search code examples
node.jses6-promise

correct place to call process.exit() in promise chain


Having problems understanding interaction of node processes and promise chains:

doSomethingAsync()
.then()
.then()
.catch()
.finally();

The finally was introduced to close db connections opened inside doSomethingAsync().

Question: In which block does a process.exit(1) on error properly belong?

  • In the .catch(), since that's where errors will go, or
  • In the .finally() since it is the last thing that should happen? (But if there is an error and catch() is triggered, do the connections get released)?
  • nowhere, because node already knows the program failed?

Solution

  • If the goal is to have the application terminate when an error occurs then I wouldn't catch the exception at all

    async function doSomething() {
      try {
        const result = await doSomethingAsync();
        // do something with result  
      } finally {
        // do cleanup
      }
    }
    

    Using async / await syntax will allow the Promise to throw the error and the uncaught exception would terminate the application. The finally block will run regardless of whether an error was thrown or not.