Async/Await
async and await let you write code that uses promises as if it were synchronous. Marking a function async makes it return a promise. Inside it, await pauses the function until a promise settles and then gives you the promise’s value, so you can assign it to a variable instead of passing a callback to then().
The pause applies only to the async function itself. The rest of the program keeps running while it waits, so the page stays responsive.
An async function returns a promise
Section titled “An async function returns a promise”Whatever an async function returns is wrapped in a promise, so the caller reads it with then() or with await:
async function getDiscount() { return 0.1;}
const result = getDiscount();console.log(result);result.then((value) => console.log(value));This prints:
Promise { 0.1 }0.1If the function throws, the promise it returns is rejected with that error.
Waiting for a request
Section titled “Waiting for a request”fetch() returns a promise of a response, and response.json() returns a promise of the parsed body. With await, each step reads like an ordinary assignment:
async function getUserName(id) { const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`); const user = await response.json(); return user.name;}
console.log('before');getUserName(3).then((name) => console.log(name));console.log('after');This prints:
beforeafterClementine Bauchafter appears before the name, because calling getUserName() starts the request and returns a pending promise straight away, and the code after the call carries on.
Handling errors
Section titled “Handling errors”A rejected promise makes await throw, so an ordinary try...catch handles failures. fetch() rejects only when the request cannot be made at all, for example when the network is down, so an HTTP error such as 404 needs its own check of response.ok:
async function getUserName(id) { try { const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`); if (!response.ok) { throw new Error(`No user ${id} (HTTP ${response.status})`); } const user = await response.json(); return user.name; } catch (err) { console.log(err.message); return null; }}
getUserName(99).then((name) => console.log(name));This prints:
No user 99 (HTTP 404)nullWhere await is allowed
Section titled “Where await is allowed”await works inside async functions, and at the top level of an ES module, which in a browser means a script loaded with <script type="module">. In a classic script it is a syntax error outside an async function. At the top level of a module, the code reads with no wrapper at all:
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');const todo = await response.json();console.log(todo.title);This prints:
delectus aut autemEach await waits for the one before it. When requests do not depend on each other, start them together instead, which Async/Await combined with Promises shows.
Steve Griffith covers this topic in his video Intro to Async and Await.