async / await
Overview
async and await are a nicer way to work with promises. Your code reads top to bottom, but it still doesn’t block the page.
async function showCourses() {
const response = await fetch('/api/courses');
const courses = await response.json();
console.log(courses);
}Compare it with the same thing as a promise chain:
function showCourses() {
return fetch('/api/courses')
.then((response) => response.json())
.then((courses) => console.log(courses));
}They do exactly the same thing. The async version just lets you name each intermediate value and write the steps as normal statements.
How it works
Marking a function async makes it return a promise. Inside it, await waits for a promise to settle and gives you its value.
async function getNumber() {
return 42;
}
getNumber(); // Promise {<fulfilled>: 42}
getNumber().then((n) => console.log(n)); // 42When the function hits await, it pauses and hands control back to the event loop. Other code — clicks, timers, other functions — keeps running. When the promise settles, the function carries on from where it stopped.
async function demo() {
console.log('2. before await');
await wait(1000);
console.log('4. after await');
}
console.log('1. start');
demo();
console.log('3. demo is paused, but this runs');await only pauses the async function it’s in — never the whole program.
Calling an async function
Because it returns a promise, the caller either awaits it (inside another async function) or uses .then():
const courses = await loadCourses(); // inside an async function or module
loadCourses().then(render); // anywhereForgetting await is a common mistake — you get a pending promise instead of the data:
const courses = loadCourses(); // Promise, not an array!
courses.length; // undefinedHandling errors
A rejected promise throws at the await, so you can use a normal try / catch:
async function showCourses() {
try {
const response = await fetch('/api/courses');
console.log(await response.json());
} catch (error) {
console.error('Could not load courses', error);
} finally {
hideSpinner();
}
}If you don’t catch inside, the error rejects the promise the function returns, so the caller can handle it instead. Decide which level is best placed to deal with it.
Running things in parallel
await one after another runs steps in sequence. To start several at once, use Promise.all:
const [user, courses] = await Promise.all([loadUser(), loadCourses()]);Only go sequential when a step needs the previous result — for example, loading a user’s courses needs the user’s id first. Otherwise, start everything together.
// Sequential — needed: the second call uses the first result
const user = await loadUser();
const courses = await loadCoursesFor(user.id);
// Parallel — independent requests
const [news, weather] = await Promise.all([loadNews(), loadWeather()]);Use Promise.allSettled if you want every result even when some fail.
Loops
await works naturally in for…of, running one iteration at a time:
for (const id of ids) {
const course = await loadCourse(id); // one after another
render(course);
}But forEach does not wait for async callbacks — it fires them all and moves on:
ids.forEach(async (id) => {
await save(id); // these all start at once; forEach doesn't wait
});
console.log('done?'); // runs before any save finishesTo process items in parallel and wait for all of them, combine map with Promise.all:
const courses = await Promise.all(ids.map((id) => loadCourse(id)));Async arrow functions and methods
const load = async (url) => (await fetch(url)).json();
class Api {
async get(path) {
const res = await fetch(`/api${path}`);
return res.json();
}
}
button.addEventListener('click', async () => {
const data = await load('/api/data');
render(data);
});
awaitonly works insideasyncfunctions — or at the top level of a JavaScript module.
Summary: three ways to write the same thing
// Callbacks
loadUser(id, (err, user) => { if (err) return showError(err); render(user); });
// Promises
loadUser(id).then(render).catch(showError);
// async / await
try {
render(await loadUser(id));
} catch (err) {
showError(err);
}Convert to async / await
Rewrite this promise chain as an async function with try / catch. Then write loadBoth() that loads courses and the user in parallel.
function loadCourses() {
return fetch('/api/courses')
.then((res) => res.json())
.catch(() => []);
}
function loadUser() {
return fetch('/api/user').then((res) => res.json());
}async function loadCourses() {
try {
const res = await fetch('/api/courses');
return await res.json();
} catch {
return [];
}
}
async function loadBoth() {
const [courses, user] = await Promise.all([loadCourses(), loadUser()]);
return { courses, user };
}Summary
asyncfunctions always return a promise.awaitpauses only that function until a promise settles, then gives you its value.- Use
try/catcharoundawaitto handle errors. - Independent steps should run in parallel with
Promise.all, not oneawaitafter another. - Use
for…of(notforEach) when you need to await inside a loop.