DEV Community

Cover image for Promise Chaining
Rakshambika
Rakshambika

Posted on

Promise Chaining

What is Promise Chaining?

  • Promise chaining means connecting multiple .then() methods together so that the result of one asynchronous operation is passed to the next operation.
  • It is especially useful when one asynchronous task depends on the result of another task.

Simple idea

Promise 1
   ↓
.then()
   ↓
Promise 2
   ↓
.then()
   ↓
Promise 3
   ↓
.then()
   ↓
Final Result
   ↓
.catch()
Enter fullscreen mode Exit fullscreen mode

Why do we need Promise Chaining?

Imagine an application needs to do these tasks:

1. Get user
       ↓
2. Get user's orders
       ↓
3. Get payment details
Enter fullscreen mode Exit fullscreen mode

The second operation needs the result of the first.

getUser()
   ↓
Need user.id
   ↓
getOrders(user.id)
   ↓
Need order.id
   ↓
getPayment(order.id)
Enter fullscreen mode Exit fullscreen mode

This is a perfect situation for Promise chaining.


Simple Promise Chaining :

Let's start with a very simple example.

const promise = Promise.resolve(10);

promise
    .then(value => {
        console.log(value);
        return value * 2;
    })
    .then(value => {
        console.log(value);
        return value + 5;
    })
    .then(value => {
        console.log(value);
    });
Enter fullscreen mode Exit fullscreen mode

Output

10
20
25
Enter fullscreen mode Exit fullscreen mode

What happened?

First:

Promise.resolve(10)
Enter fullscreen mode Exit fullscreen mode

It returns:10

Then the first .then() receives 10.

.then(value => {
    console.log(value); // 10

    return value * 2;
})
Enter fullscreen mode Exit fullscreen mode

It returns:20

That 20 is automatically passed to the next .then().

.then(value => {
    console.log(value); // 20

    return value + 5;
})
Enter fullscreen mode Exit fullscreen mode

It returns: 25

The final .then() receives 25.


Promise Chaining vs Callback Hell

Callback Hell

getUser(function(user) {

    getOrders(user.id, function(orders) {

        getPayment(orders[0].id, function(payment) {

            console.log(payment);

        });

    });

});
Enter fullscreen mode Exit fullscreen mode

Notice the nesting.

Promise Chaining

getUser()
    .then(user => getOrders(user.id))
    .then(orders => getPayment(orders[0].id))
    .then(payment => console.log(payment))
    .catch(error => console.log(error));
Enter fullscreen mode Exit fullscreen mode

Much easier to read.


Top comments (0)