Promises
Overview
A promise is an object that stands in for a value you don’t have yet. It starts pending, then becomes either fulfilled with a value or rejected with an error.
fetch('/api/courses')
.then((response) => response.json())
.then((courses) => console.log(courses));fetch can’t give you the courses immediately — the network takes time. Instead it gives you a promise straight away: an IOU saying “the response will be here later”. You attach what to do when it arrives with .then().
The three states
| State | Meaning | What runs |
|---|---|---|
| pending | the work isn’t finished | nothing yet |
| fulfilled | it worked; there’s a value | .then callbacks |
| rejected | it failed; there’s an error | .catch callbacks |
A promise settles once. After it’s fulfilled or rejected, it never changes. If you attach a .then after it has settled, the callback still runs (asynchronously) with the stored value.
Chaining
Each .then() returns a new promise, so you can line up steps one after another instead of nesting them.
Whatever your callback returns becomes the value of that new promise — and if it returns another promise, the chain waits for it:
fetch('/api/user')
.then((res) => res.json()) // returns a promise → chain waits for it
.then((user) => fetch(`/api/courses?user=${user.id}`))
.then((res) => res.json())
.then((courses) => render(courses));Compare this with the nested callbacks at the end of the previous topic: each step is on its own line, at the same indentation.
Return from
.then(). If a callback forgets toreturn, the next step receivesundefinedand doesn’t wait. This is the most common promise bug.
.then((res) => { res.json(); }) // ✗ returns undefined
.then((res) => res.json()) // ✓ implicit return
.then((res) => { return res.json(); }) // ✓ explicit returnHandling errors
Add .catch() at the end of the chain. It runs if any step before it fails:
fetch('/api/courses')
.then((res) => res.json())
.catch((error) => console.error('Request failed', error));A rejection skips every .then until it reaches a .catch. Throwing inside a .then callback also rejects the chain, so ordinary throw works:
fetch('/api/courses')
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(render)
.catch(showError) // catches network errors, the throw above, and render errors
.finally(hideSpinner); // runs whether it worked or notA .catch can also recover: whatever it returns becomes a normal value for the steps after it.
loadSettings()
.catch(() => DEFAULT_SETTINGS) // fall back
.then(applySettings); // always gets some settingsUnhandled rejections show up in the console as Uncaught (in promise). Treat them like any other uncaught error.
Making your own
Wrap a callback-based API to turn it into a promise:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
wait(500).then(() => console.log('Half a second later'));The function passed to new Promise (the executor) receives two functions: call resolve(value) on success or reject(error) on failure.
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error(`Could not load ${src}`));
img.src = src;
});
}You rarely need new Promise when an API already returns promises — just chain them.
Promise.resolve(value) and Promise.reject(error) create already-settled promises, which is handy in tests and for returning early.
Combining promises
| Method | Fulfils when… | Rejects when… |
|---|---|---|
Promise.all([…]) |
all fulfil — with an array of values | any rejects |
Promise.allSettled([…]) |
all have settled — with each result’s status | never |
Promise.race([…]) |
the first to settle fulfils | the first to settle rejects |
Promise.any([…]) |
the first to fulfil | all reject |
Promise.all([fetchUser(), fetchCourses()])
.then(([user, courses]) => render(user, courses));
// A timeout: whichever finishes first wins
Promise.race([fetch(url), wait(5000).then(() => { throw new Error('Timed out'); })]);Promises run once. After a promise settles, its value never changes — calling
.then()again just gives you the same result.
The next topic, async / await, gives you a way to write all of this as ordinary-looking, top-to-bottom code — but it’s built entirely on promises, so everything here still applies.
Handle the error
Add a .catch() so a failed request logs a friendly message, and a .finally() that logs 'Done' either way. Bonus — make the chain throw if the response isn’t OK.
fetch('/api/courses')
.then((res) => res.json())
.then((data) => console.log(data));fetch('/api/courses')
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((data) => console.log(data))
.catch(() => console.log('Could not load courses.'))
.finally(() => console.log('Done'));Summary
- A promise is pending, then either fulfilled with a value or rejected with an error — once.
.then()runs on success and returns a new promise, so steps chain.- Return a value (or a promise) from
.then()to pass it to the next step. - Always add
.catch()to handle failures;.finally()runs either way. Promise.all,allSettled,raceandanycombine several promises.