JavaScript runs on one thread. It cannot do two things at once, so when it has to wait for something — a network request, a timer, a file — it hands the work off, carries on with whatever is next, and comes back when the result arrives. Understanding that one mechanism explains almost every surprising async behaviour you will meet.
The event loop#
console.log("first");
setTimeout(() => console.log("third"), 0);
Promise.resolve().then(() => console.log("second and a half"));
console.log("second");
first
second
second and a half
third
Even with a zero-millisecond timer, the callback runs last. The rule is: JavaScript finishes all the synchronous code first, then runs queued microtasks (promise callbacks), then queued macrotasks (timers, events). Nothing interrupts running code — it always waits for the current work to finish.
That is why a long synchronous loop freezes a web page: no click handler, no timer and no animation can run until it ends.
Callbacks#
getUser(id, function (error, user) {
if (error) return handle(error);
getOrders(user.id, function (error, orders) {
if (error) return handle(error);
getDetails(orders[0].id, function (error, details) {
if (error) return handle(error);
console.log(details);
});
});
});
The original approach. It works, and three levels of nesting with an error check at each is why people call it callback hell. Every modern API returns a promise instead.
Promises#
A promise represents a value that is not available yet. It is pending, then either fulfilled with a value or rejected with an error — and once settled it never changes.
getUser(id)
.then(user => getOrders(user.id))
.then(orders => getDetails(orders[0].id))
.then(details => console.log(details))
.catch(error => handle(error))
.finally(() => hideSpinner());
Flat instead of nested, and one .catch handles a failure anywhere in the chain. Note that returning a promise from inside .then is what makes the chain wait for it — forget the return and the next step receives undefined.
async and await#
async function loadDetails(id) {
try {
const user = await getUser(id);
const orders = await getOrders(user.id);
const details = await getDetails(orders[0].id);
return details;
} catch (error) {
handle(error);
} finally {
hideSpinner();
}
}
The same chain, written as if it were ordinary sequential code. Three things to remember: an async function always returns a promise, you can only await inside one, and await pauses that function without blocking anything else.
Top-level await works in modules:
const config = await fetch("/config.json").then(r => r.json());
Sequential or concurrent#
// Sequential - total time is the sum
const a = await fetchA(); // 1 second
const b = await fetchB(); // 1 second
// 2 seconds
// Concurrent - total time is the slowest
const [a, b] = await Promise.all([fetchA(), fetchB()]);
// 1 second
This is the single largest performance improvement available in most async code. Await in sequence only when the second call genuinely needs the first one’s result.
// Every result, successes and failures alike
const results = await Promise.allSettled(tasks);
results.forEach(r => {
if (r.status === "fulfilled") console.log(r.value);
else console.error(r.reason);
});
// The first to finish
const winner = await Promise.race([fetchFast(), timeout(5000)]);
// The first to succeed
const first = await Promise.any([mirrorA(), mirrorB()]);
Promise.all rejects as soon as any one fails, discarding the others’ results. allSettled waits for everything and reports each outcome — usually what you want when partial success is acceptable.
The four mistakes#
1. Forgetting await#
const user = getUser(id);
console.log(user.name); // undefined - user is a Promise
The symptom is a value that is a Promise object rather than your data, or undefined where you expected a property. If a variable prints as Promise { <pending> }, an await is missing.
2. Awaiting inside a loop#
// Ten requests, one after another
for (const url of urls) {
results.push(await fetch(url));
}
// Ten requests at once
const results = await Promise.all(urls.map(url => fetch(url)));
Sequential awaiting in a loop is sometimes correct — when each step depends on the previous, or when you must not overwhelm a server. Usually it is an oversight.
To limit concurrency rather than removing it:
async function mapLimit(items, limit, fn) {
const results = [];
const executing = new Set();
for (const item of items) {
const p = Promise.resolve().then(() => fn(item));
results.push(p);
executing.add(p);
p.finally(() => executing.delete(p));
if (executing.size >= limit) await Promise.race(executing);
}
return Promise.all(results);
}
const pages = await mapLimit(urls, 5, url => fetch(url).then(r => r.text()));
3. async inside forEach#
// Does not wait - forEach ignores the returned promises
items.forEach(async (item) => {
await save(item);
});
console.log("done"); // prints before anything is saved
// Waits
for (const item of items) {
await save(item);
}
// Or, concurrently
await Promise.all(items.map(item => save(item)));
forEach has no idea what a promise is. It calls your function and discards the result, so nothing waits.
4. Unhandled rejections#
// The error vanishes
someAsyncThing();
// Handled
someAsyncThing().catch(error => console.error(error));
// Or awaited inside a try block
try {
await someAsyncThing();
} catch (error) { }
Calling an async function without awaiting or catching it means a rejection has nowhere to go. In Node it terminates the process by default; in a browser it appears as an unhandled rejection warning in the console and nothing else.
const response = await fetch(url);
if (!response.ok) throw new Error("Request failed: " + response.status);
const data = await response.json();
Timeouts and cancellation#
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch(url, { signal: controller.signal });
const data = await response.json();
} catch (error) {
if (error.name === "AbortError") console.log("Timed out");
else throw error;
} finally {
clearTimeout(timer);
}
// Shorter, in modern environments
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
Turning a callback API into a promise#
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, "utf8", (error, data) => {
error ? reject(error) : resolve(data);
});
});
}
await delay(1000);
Only wrap callback APIs this way. Wrapping something that already returns a promise in new Promise is a well-known anti-pattern — it adds nothing and usually loses the error handling.
Questions people ask#
Does async make JavaScript multi-threaded?
No. There is still one thread. Async means it does not sit idle while waiting for something external. For genuine parallelism you need Web Workers.
Why does my await not pause anything?
Awaiting a non-promise resolves immediately. Check that the function you are awaiting actually returns a promise — a missing return inside it is the usual cause.
Should I use promises or async/await?
async/await for sequential logic, which is most code. Promise combinators — all, allSettled, race — for concurrency. They are the same mechanism, so mixing them is normal.
What is a microtask?
A promise callback. Microtasks run after the current synchronous code and before any timer, which is why a resolved promise beats setTimeout(fn, 0).
Where to go next#
- The JavaScript fetch API — the most common async operation.
- Introduction to ES6 and beyond — where promises and async arrived.
- Why is my JavaScript not working? — debugging async code.