0

I'm quite new to promises in javascript and I'm still trying to work out the best way to chain promises together in javascript, e.g.

something().then(function(result){
  console.log(result);
})

function something(){
  return another().then(function(result){
    return "message";
  })
}

if something() and another() both return promises, will the another() and its then() be called before the console.log() statement, i.e. will they join the outter chain of promises or will the outter chain complete because it has successfully created the inner chain?

Our actual chain are often longer and flatter but I'd like to encapsulate some repetitive code, for example, we make a lot of HTTP calls which return promises and we want to perform some common validation before continuing the chain but we don't want to repeat that second step in every chain.

1 Answers1

0

The inner promise will be chained into the outer promise and the outer promise will not be fulfilled until the inner one is fulfilled also.

Returning a promise from a .then() handler automatically chains to that promise chain and the outer one will not be resolved until the inner one is also resolved. This is super important and useful capability of promises.

Working demo: http://jsfiddle.net/jfriend00/L6u2sw73/

jfriend00
  • 683,504
  • 96
  • 985
  • 979