async/await in JavaScript
Introduction
async/await is syntax for working with Promises without long .then chains. An async function always returns a Promise; await pauses that function until a Promise settles. This chapter focuses on patterns, pitfalls, and parallel vs sequential flows used in real apps.
Prerequisites
Basic async Function
javascript
// async always returns a Promise
async function doubleAfterDelay(n) {
await new Promise((resolve) => setTimeout(resolve, 50));
return n * 2;
}
const result = await doubleAfterDelay(3);
console.log(result);Top-level await works in ES modules (type: "module" or .mjs).
try/catch with await
javascript
async function loadProfile(id) {
try {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error("loadProfile:", err.message);
return null;
}
}
console.log(await loadProfile(1));Rejected Promises from await throw inside try like sync exceptions.
Sequential vs Parallel
javascript
Use Promise.all when tasks are independent.
Promise.allSettled for Partial Success
javascript
Async in Array Methods
javascript
IIFE for Scripts Without Top-Level await
javascript
// Classic script without module
(async () => {
const data = await fetch("https://jsonplaceholder.typicode.com/todos/1").then(
(r) => r.json()
);
console.log(data);
})();Mini Example: Retry with await
javascript
FAQ
await blocks the whole program?
Only the current async function—other events and callbacks still run on the main thread.
Return value of async?
Wrapping in Promise.resolve—return 5 becomes Promise fulfilled with 5.
Mix await and .then?
Valid but pick one style per function for readability.