This article takes about 2 minutes to read


There are many differences between await, return and return await that are easy to overlook.

Start by defining an asynchronous function:

async function waitAndMaybeReject() {
  // Wait 1 second
  await new Promise(r= > setTimeout(r, 1000));

  const isHeads = Boolean(Math.round(Math.random()));

  if (isHeads) {
    return 'yay';
  } else {
    throw Error('Boo! '); }}Copy the code

The function waits for 1 second and then half of the time returns “yay” and half of the time throws an exception.

Call Just Calling directly

async function foo() {
  try {
    waitAndMaybeReject();
  }
  catch (e) {
    return 'caught'; }}Copy the code

The function always returns Promise fulfill with undefined, without waiting.

Never return “yay”.

2 Awaiting

async function foo() {
  try {
    await waitAndMaybeReject();
  }
  catch (e) {
    return 'caught'; }}Copy the code

Foo is called, the return Promise waits 1 second, and then fulfill with undefined, or fulfill with “caught”.

Because we await the result of waitAndMaybeReject(), if rejected, our catch block catches the exception, and then “caught”. If pity, our function does not return the Promise value.

3 Returning

async function foo() {
  try {
    return waitAndMaybeReject();
  }
  catch (e) {
    return 'caught'; }}Copy the code

Foo is called and the return Promise waits for 1 second, then fulfill with “yay”, or reject with Error(‘Boo! ‘).

4 Return-awaiting

async function foo() {
  try {
    return await waitAndMaybeReject();
  }
  catch (e) {
    return 'caught'; }}Copy the code

Foo is called and the return Promise waits for 1 second, then fulfill with “yay”, or fulfill with “caught”.

This is the best way to write it.

We can break it down:

async function foo() {
  try {
    // Wait for the result of waitAndMaybeReject()
    // This will be a pity value to the partial ledValue:
    const fulfilledValue = await waitAndMaybeReject();
    // If waitAndMaybeReject() fails, throw an exception:
    return fulfilledValue;
  }
  catch (e) {
    return 'caught'; }}Copy the code

Dev-reading /fe is a reading, reading, speed-reading REPO. Don’t rely on dev-reading/fe for knowledge. This REPo is just a quick tool to get to know the content of the article. It does not provide full text interpretation or translation. You can quickly understand the content of the article through this platform, find the article you are interested in, and then go to read the full text.

Await vs return vs return await

Discuss addresses: await, return, and trap #12 of return await

If you’d like to participate in the discussion, click here