JavaScript promises and async/await: a practical guide
How promises work, what await really waits for, running tasks in parallel with Promise.all, handling errors properly, and the event loop in two minutes.
Anything slow in JavaScript (network requests, timers, file access) is asynchronous: you start
it, carry on, and handle the result later. Promises and async/await are how modern code does
that without drowning in callbacks.
A promise is a value that arrives later
A promise is in one of three states: pending, fulfilled (with a value) or rejected
(with an error). You react to it with then and catch, or, much more readably, with await:
async function loadSeats(filmId) {
const response = await fetch(`/api/films/${filmId}/seats`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}An async function always returns a promise. await pauses that function until the promise
settles, then gives you the value, or throws the error.
Sequential vs parallel
Two awaits in a row run one after the other:
const a = await getPrice("dune"); // wait…
const b = await getPrice("heat"); // …then wait againIf the two calls don't depend on each other, start both and wait once:
const [a, b] = await Promise.all([getPrice("dune"), getPrice("heat")]);| Helper | Resolves when | Rejects when |
|---|---|---|
Promise.all | every promise fulfils | the first one rejects |
Promise.allSettled | every promise settles | never |
Promise.race | the first one settles | the first one rejects |
Promise.any | the first one fulfils | all of them reject |
Errors: try/catch around await
try {
const seats = await loadSeats("dune");
render(seats);
} catch (error) {
showMessage("Couldn't load seats. Try again.");
console.error(error);
}A rejected promise that nobody handles becomes an unhandled rejection; Node.js prints a warning
and (since v15) exits the process. Always await or .catch() the promises you create.
The forgotten await
async function save() {
writeToDisk(data); // returns a promise… which nobody waits for
console.log("Saved!"); // printed before the write finishes
}Linters can flag this ("no-floating-promises"). If you really mean fire-and-forget, write
void writeToDisk(data).catch(log) so the intent and the error handling are explicit.
The event loop in two minutes
JavaScript runs your code on a single thread. When an async operation finishes, its callback waits in a queue; the event loop runs queued callbacks whenever the current code is done.
console.log("1");
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("2");
// 1, 2, promise, timeoutPromise callbacks (microtasks) run before timers (macrotasks), which is why "promise" comes before "timeout" even with a 0 ms delay. The practical lesson: a long synchronous loop blocks everything, including the clicks and requests waiting in the queue.
Timeouts and cancellation
fetch accepts an AbortSignal; AbortSignal.timeout(ms) gives you one that fires after a delay:
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });Common mistakes
awaitinsideforEach(it doesn't wait; usefor...oforPromise.allwithmap).- Awaiting independent calls one by one.
- Swallowing errors with an empty
catch.
Async code is a major theme of JavaScript Intermediate and JavaScript Advanced.
Questions and answers
- What is the difference between Promise.all and Promise.allSettled?
- Promise.all rejects as soon as any promise rejects, so you get all results or the first error. Promise.allSettled waits for every promise and returns each outcome as fulfilled or rejected, which suits batch jobs where some failures are expected.
- Does await block the whole program?
- No. await pauses only the async function it's in; the rest of the program, including other async functions and incoming events, keeps running.
Practise it
Read next
- JavaScript closures and scope explained with small examples
What a closure is, why let and const are block-scoped while var isn't, the classic loop bug, and how closures give you private state, counters and memoised functions.
- JavaScript modules: import, export and ES modules in Node.js
Named versus default exports, how ES modules differ from CommonJS require, setting up Node.js for import, and how to organise a project into small modules.