javascript

Promise Chaining

new Promise(function (resolve, reject) {
    setTimeout(() => resolve(1), 1000); // (*)
}).then(function (result) { // (**)
    alert(result); // 1
    return result * 2;
}).then(function (result) { // (***)
    alert(result); // 2
    return result * 2;
}).then(function (result) {
    alert(result); // 4
    return result * 2;
});

The idea is that the result is passed through the chain of .then handlers.

Here the flow is:

1. The initial promise resolves in 1 second (*) ,

2. Then the .then handler is called (**) .

3. The value that it returns is passed to the next .then handler (***)

4. …and so on.

As the result is passed along the chain of handlers, we can see a sequence of alert calls: 1

→ 2 → 4 .

Was this helpful?