我怎样才能在链条的早期解决承诺?

时间:2017-10-09 17:01:37

标签: javascript node.js promise bluebird

我正在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,也许返回{ {1}}“。

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

我是Bluebird,FWIW,所以请随意使用他们的额外资料。

2 个答案:

答案 0 :(得分:1)

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

  

如果不返回被拒绝的值或从捕获中抛出,则“从失败中恢复”并继续链

这将是最好的实施;)

答案 1 :(得分:0)

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

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 */
});
相关问题