Async / Await
async/await is syntactic sugar over Promises that makes asynchronous code look and behave like synchronous code. It dramatically improves readability and simplifies error handling.
How does async/await work in JavaScript?
Mark a function async and you can use await inside it to pause until a promise settles, so asynchronous code reads like normal top-to-bottom code. An async function always returns a promise. Handle errors with try/catch, and use Promise.all to run independent requests in parallel instead of awaiting them one by one.
async function loadProfile(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error(err);
return null;
}
}
const [user, posts] = await Promise.all([getUser(), getPosts()]); // parallelPromise Chain Style
async/await Style
Sequential vs Parallel
The most common async/await mistake is making independent operations run sequentially when they could run in parallel. Always check: do these operations depend on each other?
Common Pitfalls
Interactive Examples
Code Editor
<button id="seq">Sequential</button> <button id="par">Parallel</button>
<pre id="out"></pre>Preview
async/await under the hood
async function returns a Promise
Any function marked async always returns a Promise, even if it returns a plain value. return 42 inside async becomes Promise.resolve(42). You can always .then() an async function's return value.
🎯 Quick Check
What happens if you forget await before a Promise-returning function inside an async function?
Async/Await: summary
Key points
awaitonly pauses the current async function; the rest of the page keeps running.- Sequential
awaits in a row are slow when the requests don't depend on each other. awaitin aforEachdoesn't wait. Usefor…of, orPromise.all(items.map(…)).- Top-level
awaitworks in ES modules.
Frequently asked questions
›Why does my async function return a Promise instead of the value?
Every async function returns a promise. Get the value with await fn() inside another async function, or with fn().then(…).
›Does fetch throw on a 404?
No. fetch only rejects on network failure. Check res.ok (or res.status) and throw yourself.