处理承诺链中的早期回报的最佳方法是什么? [英] Best way to handle early returns in chains of promises?

查看:47
本文介绍了处理承诺链中的早期回报的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Bluebird中处理早期回报而又不会引发错误的最佳方法是什么.例如,我在以下条件中有条件:

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)
  })

推荐答案

一旦形成.then链,其自然行为是随着每个阶段的建立逐步进行直至完成.

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 :

  • 抛出错误或返回被拒绝的承诺,以绕过所有成功处理程序,直到下一个捕获(或链的末尾)
  • 退还保证永远不会兑现的承诺-例如return new Promise()
  • 响应性地构成.then链(Esailija的回答)
  • 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)

这篇关于处理承诺链中的早期回报的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆