简体   繁体   English

蓝鸟承诺链:结果'抓住'

[英]Bluebird Promise Chains: 'Catch' with Result

In order to make this question as useful to as many people as possible, I will exclude my specific implementation details beyond that fact that I am using the Bluebird promise library with Node + Express below. 为了使这个问题对尽可能多的人有用,我将排除我的具体实现细节,而不是我在下面使用带有Node + Express的Bluebird promise库。

So, let's say that I have the following chain (where P returns a promise, and res is the Express HTTP response object): 所以,假设我有以下链(其中P返回一个promise,而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");
    }
});

Where I have placed the TODO comment above is where I would like to catch an error that might occur from my call to P . 我在上面放置了TODO评论的地方就是我想要捕捉到我打电话给P可能出现的错误。 If I do catch an error, I would like to log pVal1 and then send a 500 error, as is done in the first catch. 如果我发现错误,我想记录pVal1 ,然后发送500错误,就像第一次捕获一样。 However, I am not sure if this is possible with how I am structuring my chain. 但是,我不确定这是否可能与我如何构建我的链。

I believe that I need to do some "branching," but I do not think that I understand this concept well enough to stop the asynchronous nature of JavaScript from getting the best of me! 我相信我需要做一些“分支”,但我认为我不能理解这个概念,足以阻止JavaScript的异步性质让我最好! As such, any help is thoroughly appreciated. 因此,任何帮助都是非常感谢。

Don't forget to catch errors in the end of the chain. 不要忘记在链的末尾捕捉错误。 That's also the place to send the response. 这也是发送回复的地方。

Catching errors in the middle of a chain is for intermittent error handling; 在链中间捕获错误是为了间歇性的错误处理; the chain continues to run, so don't send a response just yet. 链继续运行,所以暂时不发送回复。

Here is something to try it out: 这是尝试它的东西:

 // example middleware function handle(req, res, next) { log("----------------"); return async("p1", "foo").then(function (pVal1) { return pVal1; }).then(function (pVal1) { var p2a = async("p2a", "bar"), p2b = async("p2a", "bar").catch(function (error) { log("Logging: " + error + " (pVal1 " + pVal1 + ")"); }); return [p2a, p2b]; }).spread(function (pVal1, pVal2) { if (pVal1 === pVal2) { res.send("Success!"); } else { res.send("Failure"); } }).catch(function (error) { res.status(500).send("An error occurred"); log("Logging: " + error); }); } // --------------------------------------------------------------------- // mockup response object var res = { status: function (code) { log("Sending status: " + code); return this; }, send: function () { log("Sending response: " + [].join.call(arguments, " ")); return this; } }; // mockup promise generator function async(name, value) { return new P(function (resolve, reject) { if ( confirm("let " + name + " succeed?") ) { log(name + " succeeds..."); resolve(value); } else { log(name + " fails..."); reject(name + " has failed"); } }); } function log() { var msg = document.createElement("DIV"); msg.textContent = [].join.call(arguments, " "); document.getElementById("log").appendChild(msg) document.body.scrollTop = document.body.scrollHeight; } 
 button { position: fixed; top: 5px; } 
 <script src="http://cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.33/bluebird.min.js"></script> <button onclick="handle(null, res, null)">Go</button> <div id="log"></div> 

This is possible if you use the explicit Promise.all instead of returning an array into .spread . 如果使用显式Promise.all而不是将数组返回到.spread

}).then(function(pVal1){
    // this becomes a `Promise.all` - the aggregation is explicit
    var all = Promise.all([pVal1, P()]);
    all.catch(function(e){  // "branching", we both return and `catch` the promise
        console.log("Error, pVal1 is", pVal1);
    });
    return all; // return it
}).spread(function(pVal1, pVal2){
       // ....
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM