After this lesson you can write and read code that uses promises: the standard JavaScript way to represent something that finishes later. You will chain steps, handle errors in one place, and start several jobs at once.
You should be comfortable with callbacks (Callbacks and functions as values) and the ideas in Timers and the event loop.
The problem promises solve
Before promises, asynchronous code used callbacks inside callbacks: do A, and when it finishes do B, and when that finishes do C. The code drifts to the right, and handling errors at every level is painful. A promise is an object that stands for a result that will arrive later. Instead of handing your callback to the slow operation, you receive a promise and attach your steps to it.
A promise is always in one of three states:
- pending: the work is still going on,
- fulfilled: it finished and has a value,
- rejected: it failed and has a reason, usually an
Error.
Once fulfilled or rejected it is settled and never changes again.
Creating a promise
Most of the time you receive promises from other code, such as fetch. But you can build one with new Promise. You pass an executor function that gets two tools: resolve to fulfil it and reject to fail it.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
function wait(ms, value, shouldFail) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) reject(new Error(value));
else resolve(value);
}, ms);
});
}
log("start");
wait(500, "hello")
.then(value => {
log("got", value);
return value.toUpperCase();
})
.then(value => log("then", value))
.catch(error => log("error", error.message))
.finally(() => log("finally"));
log("end of script");
</script>start
end of script
got hello
then HELLO
finallyThe executor runs at once, but the .then callbacks wait until the promise is fulfilled, which is why end of script prints before got hello. Try changing the call to wait(500, "boom", true). The then steps are skipped, and you see error boom and then finally.
Chaining
then, catch and finally each return a new promise, so you can chain them in a flat line instead of nesting.
- Whatever a
thencallback returns becomes the value for the next step. If it returns a promise, the chain waits for it. - If a callback throws, the new promise is rejected.
- A rejection skips over every
thenuntil it meets acatch. catchcan recover: if it returns a normal value, laterthensteps run again with that value.finallyruns either way and does not change the value passing through. It receives no arguments.
wait(60, "boom", true)
.then(() => console.log("skipped"))
.catch(error => {
console.log("caught", error.message);
return "recovered";
})
.then(value => console.log(value));
// caught boom
// recoveredThis single catch at the end of a long chain is how you handle errors for every step above it, much like one try around several lines in Errors, try and catch.
Ready-made promises
Promise.resolve(value) gives a promise that is already fulfilled, and Promise.reject(error) one that is already rejected. They are handy when a function sometimes has the answer immediately and sometimes must wait, but you want callers to always get a promise.
A thrown error inside then is turned into a rejection:
Promise.resolve()
.then(() => { throw new Error("in then"); })
.catch(e => console.log("c:", e.message)); // c: in thenRunning several promises together
Starting promises one after another is slow if they do not depend on each other. The static helpers let you wait for a group.
const wait = (ms, value, fail) =>
new Promise((resolve, reject) =>
setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));
// all: an array of results, in the original order
Promise.all([wait(30, "a"), wait(10, "b"), 3]).then(console.log);
// [ 'a', 'b', 3 ]
// all fails fast if any promise rejects
Promise.all([wait(10, "ok"), wait(5, "bad", true)])
.catch(e => console.log("all failed:", e.message));
// all failed: bad
// race: settles like the first promise that settles
Promise.race([wait(30, "slow"), wait(10, "fast")]).then(console.log);
// fast
// any: the first one that fulfils; it ignores rejections
Promise.any([wait(5, "x", true), wait(20, "y")]).then(console.log);
// yPromise.allgives results in input order, not finishing order. Plain values such as3are accepted. It rejects at the first failure.Promise.allSettlednever rejects. It resolves to an array like{ status: "fulfilled", value }or{ status: "rejected", reason }for each input. Choose it when you want every outcome, good or bad.Promise.racecopies the first promise to settle, whether it succeeded or failed. A common use is a timeout: race your request against a promise that rejects after some seconds.Promise.anytakes the first success, and rejects only if all fail.
Promises and the event loop
Callbacks from then run as microtasks, which means after the current script but before the next timer. That is why a resolved promise's then beats setTimeout(..., 0). The callbacks are never run synchronously, even if the promise is already fulfilled. Your code after .then(...) always executes first.
Common mistakes
- Forgetting to
returninsidethen..then(v => { v + 1; })returnsundefined, so the next step seesundefined. Either return the value or use the short arrow formv => v + 1. - Nesting promises instead of chaining. Return the inner promise from
thenand keep the chain flat. - No
catchat the end. A rejection with nobody handling it shows up as an "unhandled rejection" error in the console. Always end a chain withcatch. - Expecting
new Promiseto be lazy. The executor runs immediately, so the work begins as soon as you create the promise. - Running independent work one after the other. Start the promises first, then wait for them with
Promise.all. - Resolving and rejecting both. Only the first call counts. Later calls are ignored, which hides bugs.
- Using promises when the code is not asynchronous. Plain functions are simpler for plain work.
Exercise
Write delay(ms) that returns a promise fulfilled after ms milliseconds. Use it to print "one" after 500 ms, then "two" 500 ms after that, then "three", all in a single flat .then chain. Next, use Promise.all with three delays of different lengths to print "all done" once, and Promise.race to print only the fastest. Finally, make one of them reject and see how all and allSettled differ.
Next, a cleaner way to write the same logic: async and await.
Key points
- A promise is an object for a value that is not ready yet, and it is pending, then fulfilled with a value or rejected with an error.
- then registers a callback for success, catch for failure and finally for clean-up, and each returns a new promise so they chain.
- Whatever a then callback returns becomes the next step's value; forgetting return gives undefined.
- A rejection skips ahead to the nearest catch, so one catch at the end can handle a whole chain.
- Promise.all waits for every promise, allSettled reports each result, race takes the first to finish, and any takes the first success.