async and await

Write asynchronous code that reads like normal code. await pauses only its own function; errors arrive in catch.

JavaScript · beginner · 8 min · 22 steps · free

What you'll learn

AsyncAwait.js

function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) resolve({ id, name: 'Ada' });
      else reject(new Error('no such user'));
    }, 200);
  });
}

async function showUser(id) {
  try {
    const user = await fetchUser(id);
    console.log('found', user.name);
  } catch (err) {
    console.log('failed:', err.message);
  }
}

showUser(1);
showUser(-1);
console.log('requests sent');

Step by step

  1. Before the first line runs, JavaScript reads the whole file: the functions fetchUser, showUser already exist. This is called hoisting.
  2. showUser(1) starts running like any function.
  3. JavaScript calls fetchUser(), with id = 1. It gets its own variables.
  4. JavaScript calls (resolve, reject) => { setTim…, with resolve = a built-in function and reject = a built-in function. It gets its own variables.
  5. setTimeout hands the callback to a timer and returns at once. It will run after 200 ms, once the call stack is empty: see Timers waiting.
  6. fetchUser returns Promise { <pending> }.
  7. At await, showUser pauses and leaves the call stack. The rest of the program carries on.
  8. showUser(-1) starts while the first call is still waiting.
  9. JavaScript calls fetchUser(), with id = -1. It gets its own variables.
  10. JavaScript calls (resolve, reject) => { setTim…, with resolve = a built-in function and reject = a built-in function. It gets its own variables.
  11. setTimeout hands the callback to a timer and returns at once. It will run after 200 ms, once the call stack is empty: see Timers waiting.
  12. fetchUser returns Promise { <pending> }.
  13. fetchUser() has finished, so its variables are gone. showUser() #2 pauses at await and leaves the call stack. It will carry on when the value is ready.
  14. "requests sent" prints before either user arrives.
  15. 200 ms have passed and the call stack is empty, so the event loop runs the timer's callback. JavaScript calls setTimeout callback. It gets its own variables. It can still use id from fetchUser() #1, which has already returned: the closure keeps it alive. It can still use resolve and reject from (resolve, reject) => { setTim… #1, which has already returned: the closure keeps them alive.
  16. id > 0 is true, so the if-block runs.
  17. The first fetch finished: the awaited value arrives and user gets it.
  18. It prints found Ada.
  19. 200 ms have passed and the call stack is empty, so the event loop runs the timer's callback. JavaScript calls setTimeout callback. It gets its own variables. It can still use id from fetchUser() #2, which has already returned: the closure keeps it alive. It can still use resolve and reject from (resolve, reject) => { setTim… #2, which has already returned: the closure keeps them alive. id goes out of scope and disappears.
  20. id > 0 is false, so the if-block is skipped.
  21. The second fetch was rejected, so await throws the error inside showUser, and catch gets it.
  22. It prints failed: no such user.

Common mistakes

Best practices

Key takeaways

Check yourself

Does await block the whole program?

Answer: No, just its function

A rejected promise at await becomes?

Answer: A thrown error

·

More in Asynchronous JavaScript