Sometimes, we want to chain promises with promises inside then()
with JavaScript.
In this article, we’ll look at how to chain promises with promises inside then()
with JavaScript.
How to chain promises with promises inside then() with JavaScript?
To chain promises with promises inside then()
with JavaScript, we can return a promise in the then
callback.
For instance, we write:
Promise
.resolve(1)
.then((res) => {
console.log(res)
return Promise.resolve(2)
})
.then((res) => {
console.log(res)
return Promise.resolve(3)
})
.then((res) => {
console.log(res)
})
.catch((e) => {
console.error(e);
});
to call then
with callbacks that returns another promise.
Promise.resolve
returns a promise.
res
has the resolved value of the previous promise.
Each then
callback will run in the same order they’re listed.
Therefore, we see
1
2
3
logged.
Conclusion
To chain promises with promises inside then()
with JavaScript, we can return a promise in the then
callback.