Async code: return vs return await

ivandotv

Ivan V.

Posted on November 14, 2020

Async code: return vs return await

This one will be short and sweet.
Can you tell what is wrong with this piece of code?

async function getAllUsers() {
  try {
    return fetchAllUsers(); // returns promise
  }
  catch (e) {
    return new Error('never gonna happen')
  }
}
Enter fullscreen mode Exit fullscreen mode

So what is wrong with the first example? Well you see if the fetchAllUsers function rejects, the catch block inside the getAllUsers() will never run.
The return result of getAllUsers() is a promise that is not yet resolved. And if that promise rejects, it will never run the catch block of getAllUsers(), basically it will reject/throw one level up.

const users = await getAllUsers()
//it will throw here
Enter fullscreen mode Exit fullscreen mode

What you really want is:

async function getAllUsers() {
  try {
    return await fetchAllUsers(); // returns promise
  }
  catch (e) {
    return new Error('oops')
  }
}
Enter fullscreen mode Exit fullscreen mode

Have you noticed the return await? This way the try block will return a resolved promise from the fetchAllUsers()
but if that promise rejects, the catch block will run, and handle the rejection.

const users = await getAllUsers()
// users will have a value from try or catch block return statemen
Enter fullscreen mode Exit fullscreen mode

It is a subtle but important difference, and can easily be missed.

💖 💪 🙅 🚩
ivandotv
Ivan V.

Posted on November 14, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related