Notes › Web Development
JavaScript Promises & Async/Await
JavaScript runs on one thread. Slow tasks — network requests, timers, reading files — must not block it, so they run asynchronously: JavaScript starts the task, keeps going, and handles the result later. See The JavaScript Event Loop for how that works.
Callbacks and "callback hell"
getUser(1, (user) => {
getOrders(user.id, (orders) => {
getDetails(orders[0].id, (details) => {
console.log(details); // nesting keeps growing, error handling is repeated everywhere
});
});
});
Promises
A Promise is an object for a value that will arrive later. It is in one of three states:
| State | Meaning |
|---|---|
| pending | still working |
| fulfilled | finished with a value |
| rejected | failed with an error |
Once fulfilled or rejected it is settled and never changes.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const coinFlip = new Promise((resolve, reject) => {
Math.random() > 0.5 ? resolve('heads') : reject(new Error('tails'));
});
coinFlip
.then((value) => console.log('won', value))
.catch((err) => console.log('lost', err.message))
.finally(() => console.log('done'));
Chaining
Each .then returns a new promise, so steps run one after another:
fetch('/api/user/1')
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`); // fetch only rejects on network errors!
return res.json(); // returning a promise waits for it
})
.then((user) => fetch(`/api/orders?user=${user.id}`))
.then((res) => res.json())
.then((orders) => console.log(orders))
.catch((err) => console.error('Something failed:', err)); // one catch for the whole chain
Forgetting to return inside .then breaks the chain — the next step gets undefined and doesn't wait.
async / await — promises that read like normal code
async function loadOrders(userId) {
try {
const res = await fetch(`/api/orders?user=${userId}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const orders = await res.json();
return orders; // an async function always returns a promise
} catch (err) {
console.error(err);
return [];
} finally {
hideSpinner();
}
}
awaitpauses this function until the promise settles — the rest of the page keeps running.awaitworks only insideasyncfunctions (and at the top level of ES modules).
Running things in parallel
Sequential (slow — each waits for the previous):
const a = await getA(); // 1 s
const b = await getB(); // 1 s → 2 s total
Parallel (fast — start both, then wait):
const [a, b] = await Promise.all([getA(), getB()]); // ~1 s total
Promise combinators
| Method | Resolves when | Rejects when | Use for |
|---|---|---|---|
Promise.all([...]) |
all succeed → array of results | any fails (fail-fast) | load everything a page needs |
Promise.allSettled([...]) |
all finish → {status, value/reason} each |
never | send emails, show which failed |
Promise.race([...]) |
the first to settle (success or failure) | first one rejects | timeouts |
Promise.any([...]) |
the first success | all fail (AggregateError) | fastest mirror/server |
Timeout pattern:
const timeout = (ms) => new Promise((_, reject) => setTimeout(() => reject(new Error('Timed out')), ms));
const data = await Promise.race([fetch(url), timeout(5000)]);
(Modern fetch also supports AbortSignal.timeout(5000).)
Loops and async
for (const id of ids) await save(id); // one at a time (in order)
await Promise.all(ids.map((id) => save(id))); // all at once
ids.forEach(async (id) => await save(id)); // ❌ forEach doesn't wait!
For many items, process them in batches so you don't fire 1,000 requests at once.
Error handling rules
- Every promise chain needs a
.catch(ortry/catcharoundawait). - An unhandled rejection shows "Uncaught (in promise)" and in Node can crash the process.
fetchresolves even for 404/500 — checkres.ok.- Throwing inside
.thenor anasyncfunction turns into a rejection.
Converting callbacks to promises
import { promisify } from 'util'; // Node
const readFile = promisify(fs.readFile);
// or by hand:
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
Output-guessing question
console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => console.log(3));
console.log(4);
// 1 4 3 2 — promise callbacks (microtasks) run before timers (macrotasks)
Interview one-liners
- A promise is pending, then fulfilled or rejected — once.
asyncfunctions always return a promise;awaitpauses only that function.Promise.allfails fast;allSettlednever rejects.- Use
Promise.allfor independent requests — much faster than awaiting one by one. forEachdoesn't wait for async callbacks.- Related: The JavaScript Event Loop, JavaScript docs.