【问题标题】:How can I resolve a Promise early in the chain?如何在链的早期解决 Promise?
【发布时间】:2017-10-09 17:01:36
【问题描述】:

我正在 Node.js 中进行一些 HTTP 调用,并想检查请求是否失败 - 我的意思是错误必然被认为是“失败条件” ,但我想基于此执行一些业务逻辑。我有类似于以下代码的内容(尽管显然这是人为的,因为我对其进行了简化):

let p = new Promise(function(resolve, reject) {
    // In the real implementation this would make an HTTP request.
    // The Promise resolution is either a response object or an Error passed to the `error` event.
    // The error doesn't reject because the value I'm actually interested in getting is not the response, but whether the HTTP call succeeded or not.
    Math.random() <= 0.5 ? resolve({ statusCode: 200 }) : resolve(new Error());
});

p.then(ret => { if (ret instanceof Error) return false; }) // This line should resolve the promise
 .then(/* Handle HTTP call success */);

基本上我想说,“如果我解决了一个错误对象,只需退出并返回false。否则在响应对象上声明更多内容并可能返回true,也可能返回false。”

如何尽早解决承诺而不执行链的其余部分?我在想这一切都错了吗?如果 HTTP 调用错误,我不会拒绝承诺,因为 AFAICT 你无法从.catch() 中获取值(这个承诺最终会传递给Promise.all),就像使用.then() 一样,但我可能是错的。

我在 Bluebird,FWIW,所以请随意使用他们的额外内容。

【问题讨论】:

    标签: javascript node.js promise bluebird


    【解决方案1】:

    您可以从catch() 中获取值,只需返回它们,as stated on the docs

    通过不返回被拒绝的值或从捕获中抛出,您“从失败中恢复”并继续链条

    这将是最好的实现;)

    【讨论】:

      【解决方案2】:

      这里不要使用链,而只使用单个处理程序:

      p.then(ret => {
          if (ret instanceof Error) return false; // This line will resolve the promise
          /* else handle HTTP call success, and return true/false or another promise for it */
      });
      

      【讨论】:

        猜你喜欢
        • 2018-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多