JavaScript Chaining Promises
Chaining links promise steps into one line of work. Each then returns a new promise, and the next then waits for that promise.
Two steps in a chain
The first step triples the number. The second step adds one. Each step hands its result to the next step.
Promise.resolve(2)
.then((n) => n * 3)
.then((n) => n + 1)
.then((n) => console.log(n));A step that waits
A step can return a new promise. The chain pauses at that step until the new promise fulfills, then moves on.
Promise.resolve(10)
.then((n) => new Promise((resolve) => {
setTimeout(() => resolve(n + 5), 50);
}))
.then((n) => console.log(n));A chain that builds a message
Each step changes the text a little. The last step logs the finished message.
Promise.resolve("hello")
.then((s) => s + " there")
.then((s) => s.toUpperCase())
.then((s) => console.log(s));Example
function priceWithTax(price) {
return new Promise((resolve) => {
setTimeout(() => resolve(price * 1.1), 50);
});
}
Promise.resolve(100)
.then((price) => priceWithTax(price))
.then((price) => Math.round(price))
.then((price) => console.log("Total: $" + price));Key points
- Chain: a line of then calls where each step feeds the next
- Each then returns a new promise.
- A step that returns a plain value passes that value to the next step.
- A step that returns a promise makes the chain wait for that promise.
- The value at the end of a chain is the value from the last step.
- A chain runs its steps in order, one after another.
In this example, the chain starts with a price of 100. The first step returns a promise that adds tax after a short timer. The second step rounds the taxed price. The last step logs the total.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does each then return?