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?
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:
Before that, make sure to add following lines in config:
In 3.0, you will be able to do this:
Im just wondering why not taking a benefit of fact that you can
throw
whatever you like, not just something that isinstanceof Error
. It is considered as bad practice to do that? In my opinion it depends, it depends on what you are trying to accomplish. Promise chain can be interrupted by various reasons, but in general those two would fall into two groups.Classic error occur
andearly break in chain
needed. Logically second one can't be considered as something that should be aninstance of Error
.If logically, early break in chain can be considered as error(which can totally be the case), you could create your custom error and differentiate between the two in
catch
block. So just saying that one could think about another approach(s) when handling whatever interrupt that can occur in promise chain.We could argue does this can be considered as something against
first error pattern
in node. If there is an error best practice would be to invoke callback likecallback(err)
whereerr
really should beinstanceof Error
otherwisecallback(null, data)
. But on other side having in mind that.catch(fn)
is just sugar forthen(undefined, onRejected)
to me it seems good enough to handleonRejected
parameter based on situation you are in.