Javascript Promise Chaining

in javascript •  7 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.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

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))