[英]How can I resolve a Promise early in the chain?
I'm doing some HTTP calls in Node.js and want to examine whether or not the request failed or not - by this I mean that an error is not necessarily considered a "failure condition", but that I want to execute some business logic based on that. 我在做一些的Node.js HTTP调用,并要检查的请求是否失败或不-我的意思是,一个错误不一定认为是“失败的情况”,但我想执行一些业务逻辑基于此。 I have something similar to the following code (though obviously this is contrived since I simplified it):
我有一些类似于以下代码的内容(尽管显然是人为的,因为我简化了它):
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 */);
Basically I want to say, "if I resolved to an error object, just bail out and return false
. Otherwise assert some more stuff on the response object and maybe return true
, maybe return false
." 基本上,我想说:“如果我解决了一个错误对象,请纾困并返回
false
。否则,在响应对象上声明更多内容,然后返回true
,也许返回false
。”
How can I resolve the promise early and not execute the rest of the chain? 我该如何尽早兑现承诺,而不执行其余的链条? Am I thinking about this all wrong?
我在想这一切错吗? I'm not rejecting the promise if the HTTP call errors because AFAICT you can't get a value out of
.catch()
(this promise eventually gets passed to Promise.all
) in the same way you can with .then()
, but I could be wrong. 如果HTTP调用发生错误,我不会拒绝承诺,因为AFAICT不能像
.catch()
从.catch()
获得值(此承诺最终会传递给Promise.all
.then()
,但我可能是错的。
I'm on Bluebird, FWIW, so feel free to use extra stuff from them. 我在FWIW的Bluebird上,所以可以随意使用其中的多余内容。
You can get values out of a catch()
, just return them, as stated on the docs : 您可以从
catch()
获取值,只需将其返回即可, 如docs所述 :
By not returning a rejected value or throwing from a catch, you "recover from failure" and continue the chain
通过不返回拒绝的值或从捕获中抛出,您可以“从失败中恢复”并继续执行链
That would be the best implementation ;) 那将是最好的实现;)
Just don't use a chain here, but only a single handler: 只是这里不使用链,而只使用一个处理程序:
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.