Async Programming
Callbacks, promises, async/await, and the event loop in practice.
Callbacks: where async began
The original async pattern: pass a function to be called when work completes. It works — Node was built on it — but composing *sequences* of async steps nests callbacks inside callbacks inside callbacks. The result is callback hell: code that drifts rightward, duplicates error handling at every level, and resists refactoring.
Every evolution in this lesson exists to fix that composition problem while keeping the non-blocking behavior.
function step(name, ms, cb) {
setTimeout(() => cb(null, name + " done"), ms);
}
// Three sequential steps - watch the pyramid form:
step("fetch user", 50, (err, a) => {
if (err) return console.error(err);
console.log(a);
step("fetch orders", 50, (err, b) => {
if (err) return console.error(err);
console.log(b);
step("send email", 50, (err, c) => {
if (err) return console.error(err);
console.log(c);
console.log("...and error handling is repeated 3 times");
});
});
});Promises: async results as objects
A Promise represents a future result. It starts *pending*, then settles exactly once: fulfilled with a value or rejected with an error.
.then(fn)— runs when fulfilled; returns a new promise, so chains stay flat.catch(fn)— one handler catches a rejection from *any* earlier step.finally(fn)— cleanup, either way
Returning a promise from inside .then makes the chain wait for it — sequencing without nesting, and error handling written once.
function step(name, ms) {
return new Promise((resolve) =>
setTimeout(() => resolve(name + " done"), ms));
}
step("fetch user", 50)
.then((a) => { console.log(a); return step("fetch orders", 50); })
.then((b) => { console.log(b); return step("send email", 50); })
.then((c) => { console.log(c); })
.catch((err) => console.error("one catch for all steps:", err))
.finally(() => console.log("cleanup runs either way"));async/await: promises with honest syntax
async/await is syntax over promises — no new machinery, just readability:
- An
asyncfunction always returns a promise awaitpauses the *function* (never the thread!) until a promise settles, then yields its value — or throws its rejection- Ordinary
try/catchand loops work naturally around awaits
One trap: awaiting independent operations one by one serializes them needlessly. Start them all, then await together with Promise.all.
const wait = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
console.time("sequential");
await wait(100, "a");
await wait(100, "b"); // waits for a first: ~200ms total
console.timeEnd("sequential");
console.time("parallel");
const [a, b] = await Promise.all([wait(100, "a"), wait(100, "b")]);
console.timeEnd("parallel"); // both at once: ~100ms
console.log("got:", a, b);
}
main();The promise combinators
Four static helpers coordinate multiple promises:
Promise.all(list)— waits for all; rejects immediately if *any* rejects (all-or-nothing)Promise.allSettled(list)— waits for all, never rejects; yields{status, value|reason}per promise — best when partial failure is acceptablePromise.race(list)— settles with the first to settle, win or lose — the classic timeout toolPromise.any(list)— fulfills with the first success, rejects only if all fail
const ok = (v) => Promise.resolve(v);
const fail = (m) => Promise.reject(new Error(m));
async function main() {
try {
await Promise.all([ok(1), fail("boom"), ok(3)]);
} catch (err) {
console.log("all() rejected:", err.message);
}
const results = await Promise.allSettled([ok(1), fail("boom"), ok(3)]);
for (const r of results) {
console.log(r.status, r.status === "fulfilled" ? r.value : r.reason.message);
}
}
main();Microtasks vs macrotasks: the ordering rules
When multiple callbacks are ready, the event loop follows strict priorities. After every piece of synchronous code (and after *each* callback), Node drains two microtask queues before touching anything else:
- First: the
process.nextTickqueue (Node-specific, highest priority) - Then: the promise microtask queue (
.then/awaitcontinuations)
Only then do macrotasks run, by event-loop phase: timers (setTimeout/setInterval), then I/O callbacks, then setImmediate. The rule of thumb: sync code → nextTick → promises → timers → immediates.
console.log("1: sync");
setTimeout(() => console.log("5: setTimeout 0ms"), 0);
setImmediate(() => console.log("6: setImmediate"));
Promise.resolve().then(() => console.log("4: promise then"));
process.nextTick(() => console.log("3: nextTick"));
console.log("2: sync end");
// sync (1,2) -> nextTick (3) -> promise (4)
// -> timers (5) -> setImmediate (6)await yields to the microtask queue
Every await splits a function in two: the code *before* runs synchronously, and the code *after* becomes a promise continuation — a microtask. So an async function starts running immediately when called, but the moment it hits await, control returns to the caller, and the rest is scheduled.
This explains the classic interview puzzle below: "inside start" prints during the synchronous phase, but "after await" must wait its turn in the microtask queue — after the synchronous code, before any timer.
async function run() {
console.log("2: inside run (sync part)");
await null; // yields - the rest becomes a microtask
console.log("4: after await (microtask)");
}
console.log("1: before call");
run();
console.log("3: after call (run is paused at await)");
setTimeout(() => console.log("5: timer (macrotask, last)"), 0);Check your understanding
5 questionsQuestion 1 of 5
Score: 0