繁体   English   中英

在NodeJS中有什么好的模式可以处理错误响应并再次尝试相同的调用,同时又避免了回调汤?

[英]What is a good pattern in NodeJS for handling an error response and trying the same call again whilst avoiding callback soup?

我正在寻找一种处理以下情况的好模式。 而且,我想知道这是否对诺言有帮助?

场景

有一个调用返回一个回调。 该回调get传递了一个错误对象。 我想检查该错误对象,采取适当的措施解决它,然后再次进行原始调用。 而且,我想避免当前实现中的回调汤。

(错误)JavaScript示例

doSomethingInteresting(arg0, arg1, function(err, result) {
    if(err && err.code == 1111) {
        fixTheError(err, function() {
            doSomethingInteresting(arg0, arg1, function(err, result) {
                if(err && err.code == 2222) fixTheError(err, function() {
                    // on and on for each possible error scenario...
                });
            });
        });
    }
    // do other stuff...
});

诀窍是将事情设置为递归运行。

function callbackFunction (err, arg0, arg1) {
    //If we pass arg0, arg1, and this along with our fix error condition, instead of 
    //making it dependent on the closure, we can make things happen recursively!
    if (err) fixAnyErrorCondition(err, arg0, arg1)
}

//Now make your fix error condition, handle any potential error.
function fixAnyErrorCondition(err, arg0, arg1) {
    if (err.condition1) {
         //fix condition1
    } else if (err.condition2) {
         //fix condition2
    }
    //Once we fix the error conditions, call the function again, using the same arguments!
    doSomethingInteresting(arg0, arg1, callbackFunction);
}

//Now just start the process!
doSomethingInteresting(arg0, arg1, callbackFunction);

使用此逻辑,doSomethingINteresting函数以及您的错误回调将在需要时相互调用多次,而不必嵌套潜在的无限数量的回调。 CH!

有一种叫做Promise模式的东西,它是一种在异步模式下模拟syncnus行为的方式。

例如,传统上使用回调方法将编写如下代码:

asyncCall(function(err, data1){
    if(err) return callback(err);       
    anotherAsyncCall(function(err2, data2){
        if(err2) return calllback(err2);
        oneMoreAsyncCall(function(err3, data3){
            if(err3) return callback(err3);
            // are we done yet?
        });
    });
});

但是,使用Promises模式,可以这样写:

    asyncCall()
.then(function(data1){
    // do something...
    return anotherAsyncCall();
})
.then(function(data2){
    // do something...  
    return oneMoreAsyncCall();    
})
.then(function(data3){
   // the third and final async response
})
.fail(function(err) {
   // handle any error resulting from any of the above calls    
})
.done();

这两个代码示例均来自i2devs 有关更多信息,请搜索Promise Javascript Pattern。 它太大,无法包含在此处。

注意 :在错误处理方面,使用Promise模式,如果引发错误,则将其一直带到.fail()方法,如在第二个示例中看到的,就像在正常try / catch中所期望的那样例行程序。

对于Promise模式库,我建议使用Qbluebird

暂无
暂无

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

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