Best way to handle early returns in chains of promises?

送分小仙女□ 提交于 2020-01-05 17:58:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!