Async and Await
async and await are keywords that let you write promise-based code so it reads like ordinary top-to-bottom code. You mark a function with async, and inside it you put await in front of any promise to pause that function until the promise settles. You reach for them whenever you fetch data, read files, wait on a timer or chain several asynchronous steps that depend on each other.
What the async keyword changes
An async function always returns a promise, even if you return a plain value. Writing return 5 inside it is the same as returning Promise.resolve(5). If the function throws, the returned promise is rejected with that error. This means callers can use .then() on it or await it from another async function.
You can apply async to function declarations, function expressions, arrow functions and class methods. In JavaScript modules (files loaded with type="module" or .mjs files in Node), you can also use await at the top level without wrapping it in a function.
How await pauses only one function
When the engine reaches await somePromise, it suspends the current async function and hands control back to the event loop. Other code, click handlers and timers keep running. When the promise fulfils, the function resumes on the next line and await evaluates to the fulfilled value. Nothing about the browser freezes; only that one function is waiting.
async function loadUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const user = await response.json();
console.log(user.name);
return user;
} catch (error) {
console.error('Could not load user:', error.message);
return null;
}
}
loadUser(7).then((user) => console.log('Done', user));
Notice that fetch does not reject on a 404 or 500 status. It only rejects on network failure, so the code checks response.ok and throws on its own.
Error handling with try and catch
A rejected promise that you await behaves like a thrown exception at that line. That is why try...catch works naturally here, and why a finally block is a clean place to hide a loading spinner whether the request succeeded or not. If you do not catch the error, the promise returned by your async function rejects, and the caller must handle it.
The sequential await trap
The most common mistake is awaiting independent tasks one after another. Each await waits for the previous one to finish, so two requests that each take one second end up taking two seconds in total.
// Slow: the second request starts only after the first finishes
const posts = await fetch('/api/posts').then((r) => r.json());
const tags = await fetch('/api/tags').then((r) => r.json());
// Faster: start both, then wait for both together
const [postsData, tagsData] = await Promise.all([
fetch('/api/posts').then((r) => r.json()),
fetch('/api/tags').then((r) => r.json()),
]);
This connects directly to running parallel promises: Promise.all still does the parallel work, and await simply waits for the combined result. Use Promise.allSettled when you want every result even if some fail.
Another slip is calling await inside array.forEach(). The forEach callback does not wait, so the loop finishes before any of the work does. Use a for...of loop when steps must run in order, or Promise.all with map when they can run together.
Quick reference
asyncmakes a function return a promise automatically.awaitonly works inside async functions or at the top level of a module.- Wrap awaited calls in
try...catchto handle rejections. - Await independent tasks together with
Promise.all, not one by one. - Avoid
awaitinsideforEach; usefor...ofinstead.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.