DEV Community

Cover image for Async code: return vs return await
Ivan V.
Ivan V.

Posted on • Edited on

16 1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (3)

Collapse
 
tanvirrb profile image
Tanvir Islam

Which one is more preferable, in case of performance?

Collapse
 
ivandotv profile image
Ivan V. • Edited

Sorry for a late reply (notifications on dev.to are crazy stupid).

In case of return await it will have one more microtask, you can think of it as one more then() added to the promise chain. So if you need to catch the error that is what you should use. If you plan on handling errors somewhere else in your code then just use return (without await).

Collapse
 
tanvirrb profile image
Tanvir Islam

thank you <3

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay