Web Analytics

Async/Await

Modern ~15 min read

Introduction

async and await make promises easier to write.

  • async makes a function return a Promise.
  • await makes a function wait for a Promise.

Async Functions

The keyword async before a function makes the function return a promise.

HTML
CSS
JS

Await Syntax

The keyword await before a promise makes JavaScript wait until that promise settles and returns its result.

Note: await only works inside an async function.

HTML
CSS
JS

Error Handling

You can handle errors in async functions using standard try...catch blocks.

HTML
CSS
JS

Summary

  • async/await is syntactic sugar built on top of Promises.
  • It makes asynchronous code look and behave a little more like synchronous code.
  • Use try...catch for error handling.

Quick Quiz

Can you use 'await' outside of an 'async' function?

A
Yes, always
B
No, never (except top-level await in modules)
C
Only in loops
D
Only in callbacks