Handling those unhandled promise rejections with JS async/await

The Problem

If you are seeing this error:

  • You put your code inside an async function in order to use await calls
  • One of your awaited functions fails (i.e. rejects a promise)
  • You get the error
  • You put your code inside an async function in order to use await calls
  • You put an await call inside a try/catch block or you use .catch()
  • The awaited function fails (i.e. rejects a promise)
  • You throw an error in the catch block to terminate the script
  • You get the error
await returnsPromise().catch(e => { console.log(e) })
try {
await returnsPromise()
} catch (error) {
console.log('That did not go well.')
}
  • adding .catch() to your wrapper function call (you don’t even really need the try/catch block inside the wrapper then)
(async function () {
try {
await returnsPromise()
} catch (error) {
console.log('That did not go well.')
throw error
}
})().catch( e => { console.error(e) })
  • using process.exit(1) instead of throw to terminate the script (lazy but efficient…)
(async function () {try {
await returnsPromise()
} catch (error) {
console.error(error)
process.exit(1)
}
console.log('This will not be printed.');})()

Could it be cleaner?

If all you want is to terminate the script and display the error, you can simply get rid of the try/catch block altogether. The catch at the end of the IIFE will take care of the rejected promise from returnsPromise.

(async function () {  await returnsPromise()
console.log('This will not be printed.');
})().catch( e => { console.error(e) })

Do you always need to add the .catch() at the end of the IIFE?

Not if you catch and handle everything within the function.

(async function () {await returnsPromise().catch((e) => { console.error(e); process.exit(1) })console.log('This will not be printed.');})()
(async function () {   try {
await returnsPromise()
} catch (error) {
console.error(error)
process.exit(1)
}
console.log('This will not be printed.');})()
(async function () {var result = await returnsPromise().catch((e) => { console.error(e.message) })console.log( result ? 'This was a success! ' + result : 'This was a failure.' )})()

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jonáš Jančařík

Jonáš Jančařík

Data analyst, formerly technologist @ECThinkTank (http://medium.com/@ECThinkTank) @EU_Commission think tank.