Javascript Promise Chaining

in #javascript7 years ago (edited)

Promise Chaining becomes very important when you are trying to do something with the responses of multiple requests where that something will be a result of the dependency of one response on the response before it.

To demonstrate the above, I will create two functions called 'add' and 'addMore', where 'add' will return the sum of the two numbers you supply to it and the function 'addMore' will take the returned result of the function 'add' and add another number to it that is supplied to it as a param.

I will use timeouts to simulate delayed server responses:

Promise chaining.png

The trick here is to use the bind method of the function 'addMore' to pass the parameter 10.

Sort:  

Promises are awesome! One of the main advantages over callbacks is the ability to chain promises. So you could also do something like this - I think it's more readable than nesting Promises:

add(2, 3)
  .then(response => addMore(response, 10))
  .then(response => console.log(response))

Or, if you like the bind variant:

add(2, 3)
  .then(addMore.bind(null, 10))
  .then(response => console.log(response))

Coin Marketplace

STEEM 0.20
TRX 0.12
JST 0.029
BTC 60633.78
ETH 3383.05
USDT 1.00
SBD 2.52