[英]How can I resolve a Promise early in the chain?
我在做一些的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()
从.catch()
获得值(此承诺最终会传递给Promise.all
.then()
,但我可能是错的。
我在FWIW的Bluebird上,所以可以随意使用其中的多余内容。
只是这里不使用链,而只使用一个处理程序:
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 */
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.