Async/Await

Please click on this link to access the resource folder for this lesson.

  • async/await are special syntax to work with promises in a more comfortable fashion.
  • The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.
  • The keyword await makes JavaScript wait until that promise settles and returns its result.
async/await
  • await only works inside an async function. If we try to use await in a non-async function, there would be a syntax error:
  • Show example of converting the chapter Promises chaining and rewrite it using async/await:
  • If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. So handle errors with try..catch
  • When we use async/await, we rarely need .then, because await handles the waiting for us. And we can use a regular try..catch instead of .catch. That’s usually (but not always) more convenient.
  • But at the top level of the code, when we’re outside any async function, we’re syntactically unable to use await, so it’s a normal practice to add .then/catch to handle the final result or falling-through error, like in the line (*) of the example above.
Scroll to Top