Search code examples
javascriptpromisebluebird

Can I break a chain early with bluebird Promises?


I don't necessarily want to error, but I have:

getFromDb().then (tradeData) ->
  if not tradeData
    # DO NOT CONTINUE THE CHAIN
  else
    getLatestPrice tradeData
.then (latestPrice) ->
  ...
.then ->
  ...
.then ->
  ...
.catch (err) ->
  next err

Any way for me to abort the chain if there is no tradeData?


Solution

  • getFromDb().then (tradeData) ->
      if tradeData
        getLatestPrice tradeData ->
          .then (latestPrice) ->
            ...
          .then ->
            ...
          .then ->
            ...
          .catch (err) ->
            next err
      else
        getSomethingElse ->
           send("no data")
    

    In 3.0, you will be able to do this:

    p = getFromDb().then (tradeData) ->
      if not tradeData
        send("no data");
        p.break()
      else
        getLatestPrice tradeData
    .then (latestPrice) ->
      ...
    .then ->
      ...
    .then ->
      ...
    .catch (err) ->
      next err