【发布时间】:2015-09-30 14:07:02
【问题描述】:
为了使这个问题对尽可能多的人有用,我将排除我的具体实现细节,除了我在下面使用带有 Node + Express 的 Bluebird Promise 库。
所以,假设我有以下链(P 返回一个承诺,res 是 Express HTTP 响应对象):
P().then(function(){
// do nothing if all went well (for now)
// we only care if there is an error
}).catch(function(error){
res.status(500).send("An error occurred");
}).then(function(){
return P();
}).then(function(pVal1){
return [pVal1, P()];
}) // TODO: catch an error from P() here and log pVal1
.spread(function(pVal1, pVal2){
if(pVal1 === pVal2) {
console.log("Success!");
} else {
console.log("Failure");
}
});
我在上面放置TODO 注释的位置是我想捕捉调用P 时可能发生的错误的位置。如果我确实捕获了一个错误,我想记录pVal1,然后发送一个 500 错误,就像在第一次捕获中所做的那样。但是,我不确定我如何构建我的链是否可能。
我认为我需要做一些“分支”,但我认为我对这个概念的理解还不够好,无法阻止 JavaScript 的异步特性发挥最大作用!因此,非常感谢任何帮助。
【问题讨论】:
-
如果我完全做错了,请告诉我!
-
@torazaburo 不,不是。
-
@BenjaminGruenbaum 为什么不呢?
-
@DavidKnipe 参数 -
Promise.resolve("HI").then(alert);与Promise.resolve("HI").then(function(){ return alert(); }); -
我假设你说
function() { return alert(); }忽略了它的论点。这是真实的。但在这个问题中,P似乎无论如何都忽略了它的论点。如果是,那么function() { return P(); }等价于P。
标签: javascript node.js promise bluebird