A Promise is an object that represents work that may finish later, and will either succeed with a value or fail with an error. A network request is the classic example: it is not done yet, but you want to say what happens when it is.
Think of an order number at a bakery. You do not have the bread yet, but the number is a promise of it. Later you either get the bread, or they tell you it is sold out.
The three states
| State | Meaning |
|---|---|
| pending | work is in progress |
| fulfilled | it succeeded, and has a result value |
| rejected | it failed, and has a reason (usually an Error) |
A promise starts as pending, then settles once into fulfilled or rejected. It never changes after that.
Creating one
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const ok = true;
if (ok) {
resolve("Success!"); // fulfil with a value
} else {
reject(new Error("Something went wrong")); // reject with a reason
}
}, 300);
});
console.log(promise); // → Promise {} (pending right now)
promise.then(value => console.log(value)); // → Success!
The function you give to new Promise (the executor) runs immediately. It receives resolve and reject, and you call one of them when the work is done.
Using one
You attach handlers with then (success) and catch (failure):
function wait(ms) {
return new Promise(resolve => setTimeout(() => resolve("waited " + ms + " ms"), ms));
}
wait(200)
.then(message => console.log(message)) // → waited 200 ms
.catch(error => console.log("failed", error));
Most of the time you use promises that other APIs return (like fetch) instead of creating your own.
Already-settled promises
Promise.resolve(42).then(v => console.log(v)); // → 42
Promise.reject(new Error("no")).catch(e => console.log(e.message)); // → no
Why promises
- You can chain steps (then, catch and finally).
- Errors flow to one
catch. - They combine: wait for several at once with Promise.all.
- They are the basis of
async/await.
Promises are always asynchronous
Even an already resolved promise calls its then handlers later, after the current code finishes.
Promise.resolve("done").then(v => console.log(v));
console.log("this prints first");
Real-world example
fetch("/api/data") returns a promise. When the server responds, it fulfils with a Response. See fetch().