节点承诺控制流程

时间:2016-12-25 16:01:31

标签: node.js promise

我在bluebird中使用promise发送mysql查询并管理控制流程&错误。这是它的样子:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == PICK_IMAGE_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
             Uri imageUri = data.getData();
            // Do something with the image here 
    }
}

承诺链很方便,但是如果内部有多个子链,我发现错误处理会很麻烦。

在这里,我可能需要在/ * * /

中编写以下内容
sendQuery1(..)
.then(sendQuery2(..))
.then(function(results from last query){
    if(rain){
        res.render(...)
    }else{
        /*
          I need to send additional 2 queries here
        */
    }
}).catch(errors);

有没有更好的方法来处理这类问题?

3 个答案:

答案 0 :(得分:2)

我在这里没有看到你的问题。如果您在链中有一个链(通常不会在那里检查您的架构),您可以捕获所显示的错误。

我建议您使用全局(或本地)错误处理函数,并将其传递给catch函数。因此,即使您有多个捕获,也可以使用相同的错误处理程序。

在我看来,最好的解决方案是创建一个" promise chain bypass&#34 ;,因此使用catch来根据你的情况跳过某些部分。如果这不是您要找的,请说明您的问题。

答案 1 :(得分:0)

您将收到错误,代码中没有问题。是的,它会变得混乱但你可以采用以下方法来保持代码清洁并仍然实现你的逻辑:

sendQuery1(..)
.then(sendQuery2(..))
.then(function(results from last query){
    if(rain){
        res.render(...)
        throw new Error('breakChain');  //intentionally throwing error to skip the remaining chain
    }
    return; //will act like 'else'
})
.then(sendQuery3(..))
.then(sendQuery4(..))
.catch(function (e) {
    if(e.message != 'breakChain')   //act on error if it was other than 'breakChain'
        throw e;
});

答案 2 :(得分:0)

您在这里讨论的是基于某些逻辑条件的链的分支。实际上分支链通常更好,而不是仅仅为了中止链的其余部分而抛出错误。这样可以将错误保留为错误,而不是Shaharyar提出的合成错误的方案,而这种错误并非真正的错误。

您可以通过从.then()处理程序中返回一个新的保证链来对该链进行分支,如下所示:

sendQuery1(..).then(function(r1) {
    return sendQuery2(...);
}).then(function(r2){
    if (rain){
        // processing is done, so just render
        res.render(...)
    } else {
        // return promise here to attach this new branch to the original chain
        return sendQuery3(..).then(sendQuery4).then(function() {
            // process last query
        });
    }
}).catch(errors);

仅供参考,因为您只发布了伪代码,而不是实际代码,我们无法看到哪些功能需要访问哪些先前结果才能完成工作,我们无法完全优化代码。这是为了展示如何在promise链中运行分支的示例。这是你可能想要使用的原则。如果您展示了真实的代码,我们可以提供更加具体和优化的答案。