Chaining – dealing with several promises

The most powerful feature of the promise lies in its ability to chain calls, thereby making code look synchronous. A chain looks like this:

getData()
.then(getMoreData)
.then(getEvenMoreData)
.catch(handleError)

This makes the code very easy to read. You are able to tell in which order things happen; namely, getData() followed by getMoreData(), followed by getEvenMoreData(). Not only are we able to run the methods in the order that we want, but we are also able to access the data from the previous promise, like so:

function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('data');
})
})
}

function getMoreData(data) { // data is from getData
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('data');
})
})
}

getData().then(getMoreData)

We can also see how we can add the .catch() method to the end to handle errors. The nature of chained promises are such that an error propagates all the way down to the catch() method.

It is, however, quite possible to handle an error at a specific level, like so:

getData()
.then(getMoreData, (err) => {}) // local error handler
.then(getEvenMoreData )
.then(data => {} )
.catch(handleError ) // global error handler

Now we have two error handlers, one at a local level .then(getMoreData, (err) => {}) as the second argument in the then() method. This has a different effect than only adding .catch() to the bottom of our call chain. If only the .catch() method at the bottom exists, then the chain is short-circuited. As it stands, the current chain will call the local error function, the .catch() method, and the last .then() method when a promise is rejected from the getMoreData() method. The data parameter in the last .then() method will, however, not be set if the promise is rejected. Chaining is powerful and gives us the following:

  • An ordered way of calling async methods
  • The previously resolved promise data as input to our method
  • The ability to handle errors globally as well as per promise, though with different results
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.220.21