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?
.catch()
, since that's where errors will go, or.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)?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.