JavaScript - Promises - Chaining

javascript-promises

// JavaScript - Promises - Chainning:

It is sometimes desirable to chain promises together.  For example, we might 
have multiple asynchronous operations that we need to perform.  When one 
operation give us data, we will start to do some other operation on that piece 
of data, and so on.  In such cases, we can chain together promises:

function getPromise(url) {
  // return a promise here.  Send an async request to the url, and when 
  // we receive the data, resolve the promise
}

var promise = getPromise('some url');
promise
  .then(function(result) {
    return getPromise(result); // return another promise
  })
  .then(function(result) {
    // handle the final result
  });

In the above code, when the first promised is resolved, both "then" callbacks 
are invoked in the order that we specified.  The second "then" callback is not 
invoked until the first "then" callback is finished.  The return value of the 
first then callback, which is another promise, is passed to the second "then" 
callback as a parameter.

When we return a simple value inside then(), the next then() is called with that 
return value.  But if we return a promise inside then(), the next then() waits 
on it and gets called when that promise is settled.  Is this really the case?  
Does the second then callback really receive the data from the second promise or 
does it receive the second promise as a parameter?
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License