A JavaScript promise is a stand-in for a value that does not exist yet. When the real value finally turns up, such as a server response, a timer, or a file read, the promise settles and the code that is waiting on it continues. Promises give you one tidy way to say "not ready yet" without nesting callbacks inside other callbacks. The previous lesson in this module explained the queues that decide when a callback runs, and the next lesson shows how async and await make the same work easier to read.
The previous lesson in this module covered "The Event Loop Explained with Real Timings", and the next lesson in this module is about "async/await: Sequential vs Parallel Waiting".
What is a promise, and what are its three states?
Every promise sits in exactly one of three states. It is pending while the work is still running, fulfilled once the work finishes with a value, and rejected once the work finishes with a reason, which is usually an Error object. The state that you observe later is the one that matters when you attach a handler.
| State | What it means | What runs next |
|---|---|---|
| pending | The work has not finished yet | Nothing fires until it settles |
| fulfilled | The work finished and produced a value | The callback passed to then runs |
| rejected | The work failed and produced a reason | The callback passed to catch runs |
The rule that trips people up is that a promise settles exactly once. After it has been fulfilled or rejected, its state never changes again, so a second call to the resolver has no effect at all. That is what makes a promise safe to hand to several consumers, because everyone who attaches a handler later sees the same settled result.
How do you create a promise?
You call new Promise(executor). The executor receives two functions, resolve and reject, and it is your job to call one of them when the work is done. Call resolve(value) to hand a value out, and call reject(error) to hand out a failure.
function wait(ms, value) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(value);
}, ms);
});
}
wait(300, 'the toast is ready').then(function (message) {
console.log(message);
});
console.log('this line runs first');
Running that file prints the two lines in this order:
this line runs first
the toast is ready
The body of the executor runs synchronously, so the timer is only scheduled after your first line has already been printed. The then callback cannot run before the promise settles, and that is why the message lands second even though the callback was attached first.
Here is the settle-once rule in practice. The second resolve and the reject are both discarded, because the promise has already been fulfilled.
function tryTwice() {
return new Promise(function (resolve, reject) {
resolve('first answer');
resolve('second answer');
reject(new Error('too late'));
});
}
tryTwice().then(
function (value) {
console.log('resolved with:', value);
},
function (error) {
console.log('rejected with:', error.message);
}
);
The output is:
resolved with: first answer
One more habit is worth forming early. If the body of the executor throws an error, the promise rejects with that error automatically. That means a tidy wrapper around any risky work is usually enough, and you rarely need a try block inside the executor.
Why does every then() call hand back a brand-new promise?
Because then does not run your callback in place. It schedules the callback for later and returns a fresh promise that represents whatever the callback produced. Two things can come out of a callback. It can give back a plain value, or it can give back another promise. If it gives back a plain value, the new promise is fulfilled with that value. If it gives back a promise, the new promise waits for it, so the two are chained together instead of being nested.
const order = [];
Promise.resolve(5)
.then(function (n) {
order.push('first then ran with ' + n);
return n * 2;
})
.then(function (n) {
order.push('second then ran with ' + n);
return n + 10;
});
order.push('code after the chain');
setTimeout(function () {
console.log(order.join(' -> '));
}, 0);
The printed order is the important lesson here:
code after the chain -> first then ran with 5 -> second then ran with 10
Everything you write after the chain is attached runs before the first handler, because the handlers are queued as microtasks while the rest of your script stays on the call stack. If you need a value from a chain, return it and keep working with that value, rather than hoping it has been assigned by the time the next line runs.
Returning a promise from a handler is what lets you build a pipeline without nesting callbacks. The value from the inner promise is passed straight to the next handler.
function loadUser(id) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve({ id: id, name: 'user-' + id, score: id * 10 });
}, 80);
});
}
loadUser(1)
.then(function (user) {
return loadUser(user.id + 1);
})
.then(function (user) {
console.log('got', user.name, 'with score', user.score);
});
The output shows the second user and not the first:
got user-2 with score 20
Notice the shape of the code. The first handler returns loadUser(user.id + 1), which is a promise. The chain waits for it, and the second handler receives the resolved object directly instead of a promise that it would have to unwrap by hand.
How do rejections travel down the chain?
A rejection moves down the chain in exactly the same way as a value does, and it skips every handler that only accepted a success callback. A catch at the end of the chain collects it. If no catch exists anywhere along the way, the rejection is reported as unhandled.
function loadProfile(id) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (id === 2) {
reject(new Error('no profile for id ' + id));
} else {
resolve({ id: id, name: 'ada' });
}
}, 40);
});
}
loadProfile(2)
.then(function (profile) {
console.log('hello', profile.name);
})
.catch(function (error) {
console.log('caught:', error.message);
});
The success handler never runs, and the catch handler prints:
caught: no profile for id 2
Throwing inside a handler produces the same effect as rejecting. That gives you a way to check a value in the middle of a pipeline and to bail out with a clear message.
Promise.resolve('42 apples')
.then(function (value) {
throw new Error('expected a number, got: ' + value);
})
.catch(function (error) {
console.log('caught:', error.message);
});
The output is:
caught: expected a number, got: 42 apples
Put the catch at the end of the chain rather than after every step, so that one single place decides what happens when any stage fails. If you need cleanup that runs whether the chain succeeded or failed, then finally is the tool for that.
How do you wait for several promises at once?
When a step needs several results, Promise.all takes an array of promises and gives you back an array of values. It waits for all of them, and the results keep the order of the input array no matter which one settled first.
function wait(ms, value) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(value);
}, ms);
});
}
const all = Promise.all([wait(120, 'a'), wait(40, 'b'), wait(80, 'c')]);
all.then(function (values) {
console.log(values.join(','));
});
The output is:
a,b,c
Even though the second promise finished first, the values come back in the order in which you listed them. If any one of those promises rejects, then the whole Promise.all rejects with that first reason, and the other results are thrown away.
Promise quick reference
- A promise starts pending and settles exactly once, as fulfilled or rejected.
new Promise(executor)gives youresolveandrejectinside the executor.thenreturns a new promise, so handlers compose into a pipeline instead of nesting inside each other.- Return a value to continue the chain, or return a promise to wait for more work.
- Throw inside a handler to fail the chain, and catch the failure with
catchat the end. - Code written after a chain runs before the chain does, so return values instead of relying on assignment.
Promise.allwaits for every promise and preserves the input order in the results.
Try it yourself: Open a scratch file and write a function delay(ms) that returns a promise which resolves with the text "waited " followed by the number of milliseconds. Chain three calls to it, and inside each handler push a line into an array that describes what just happened. Print the array from a setTimeout callback that fires with a delay of zero, and then compare that printed order with the order in which the array was filled. Next, make the middle handler throw an error and add a catch at the end. Confirm that the third handler never runs and that the catch message names the middle step.