Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 842
Shamoon Avatar asked Feb 17 '15 22:02

Shamoon


People also ask

What is promise each?

each. Given an Iterable (an array, for example), or a promise of an Iterable , iterates serially over all the values in it, executing the given iterator on each element. If an element is a promise, the iterator will wait for it before proceeding.


1 Answers

Although an accepted answer, but I would like to tell all of googlers that, "break()" function has been changed to "cancel()"

Use Something like this:

p = getFromDb().then (tradeData) ->
  if not tradeData
    send("no data");
    p.cancel(); // Look Here!!!!!!!!!!!!!!!!
  else
    getLatestPrice tradeData
.then (latestPrice) ->
  ...
.then ->
  ...
.then ->
  ...
.catch (err) ->
  next err

Before that, make sure to add following lines in config:

Promise.config({
    cancellation: true
});
like image 177
Sahil Purav Avatar answered Sep 24 '22 17:09

Sahil Purav