JavaScript Promises: then, catch, finally and Promise.all
Some work takes time: downloading data, reading a file, waiting for a timer. JavaScript does not stop and wait. It starts the work, keeps running the rest of your code, and comes back when the result is ready. A promise is the object that represents that future result.
Three states
A promise starts pending. It then settles exactly once, either fulfilled with a value or rejected with an error. You react to the outcome by attaching callbacks:
.then(fn)runsfnwith the value when the promise fulfills..catch(fn)runs when it rejects..finally(fn)runs in both cases.
Each of these returns a new promise, so they can be chained. A rejection skips the then callbacks below it until it reaches a catch, which is why "not printed" never appears in the example.
Creating a promise
new Promise((resolve, reject) => { ... }) wraps older callback-based code. The wait helper resolves after a timer fires. Promise.resolve(value) makes an already-fulfilled promise. In practice you will mostly consume promises returned by APIs like fetch() rather than create them.
Expected output
A: start B: synchronous code finishes first C: microtask caught: network down cleanup all: ["a", "b"] D: timer after 30 ms
Reading the output order
The order of the output is the main lesson here:
- All synchronous code runs first: both labels A and B print before anything else.
- Then microtasks run: promise callbacks whose promise has already settled. That covers C, then the catch and the cleanup, each needing one more step through the chain.
- Timers run last. The two
Promise.alltimers finish at 5 and 10 milliseconds, and the 30-millisecond timer fires after them.
Promise.all and friends
Promise.all([p1, p2]) waits for every promise and fulfills with an array of results in the original order, regardless of which finished first. If any promise rejects, the whole thing rejects immediately. Promise.allSettled waits for all of them and reports each outcome, and Promise.race settles as soon as the first one does.
Common mistakes
- Forgetting to
returna promise inside.then, which breaks the chain's timing. - Leaving off
.catch, so a failure becomes an "unhandled rejection" error. - Expecting code after
.then(...)to wait for it; it does not.
Summary
- A promise is pending, then fulfilled or rejected, exactly once.
- Chain
.then,.catchand.finally; each returns a new promise. - Synchronous code first, then promise callbacks, then timers.
Promise.allruns work in parallel and keeps result order.
Quiz: Promises