问题
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) {
if (thing.condition === true) {
return thing
} else {
// early return?
}
})
.then(function(thing) {
return doStuff(thing)
})
回答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)
回答2:
things.find(1).then(function(thing) {
if (!thing.condition) return;
return doStuff(thing)
.then(...);
.then(...);
})
来源:https://stackoverflow.com/questions/29525354/best-way-to-handle-early-returns-in-chains-of-promises