2017-10-09 78 views
0

我在Node.js中做了一些HTTP调用,并且想要检查请求是否失败 - 我的意思是说错误是而不是必然被认为是“失败条件”,但是我想要基于此执行一些业务逻辑。我有类似于下面的代码的东西(虽然很明显,因为我简化它,这是做作):如何在链条的早期解决Promise?

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。“

我该如何早日解决承诺并且不执行链的其余部分?我在想这个全错吗?如果由于AFAICT您无法从.catch()(这个承诺最终会传递到Promise.all)中获得一个值,但我不拒绝承诺,如果HTTP调用错误,因为AFAICT的方式与.then()相同,但我可能是错的。

我在Bluebird,FWIW上,所以随时可以使用额外的东西。

回答

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 */ 
}); 
1

你可以得到值了catch()的,只是回报他们,as stated on the docs

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

这将是最好的实施entation;)