Skip to content Skip to sidebar Skip to footer

Best Way To Handle Early Returns In Chains Of Promises?

What's the best way to handle early returns in Bluebird without throwing an error. For example, I have a conditional in the following: things.find(1) .then(function(thing) {

Solution 1:

Once a .then chain is formed, its natural behaviour is to run progressively to completion as each of its stages settles.

For an "early return" (not a good phrase but we know what you mean), you have three options :

  • throw an error, or return a rejected promise, to bypass all success handlers until the next catch (or the end of the chain)
  • return a promise that is guaranteed never to settle - eg return new Promise()
  • compose the .then chain responsively (Esailija's answer)

Solution 2:

things.find(1).then(function(thing) {
  if (!thing.condition) return;
  return doStuff(thing)
    .then(...);
    .then(...);
})

Post a Comment for "Best Way To Handle Early Returns In Chains Of Promises?"