【发布时间】: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