简体   繁体   English

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

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

I am looking for a good pattern for dealing with the following scenario. 我正在寻找一种处理以下情况的好模式。 And, I want to know if this is something that promises would help with? 而且,我想知道这是否对诺言有帮助?

Scenario : 场景

There is a call that returns a callback. 有一个调用返回一个回调。 That callback get's passed an error object. 该回调get传递了一个错误对象。 I want to examine that error object, take an appropriate action to resolve it, and make the original call again. 我想检查该错误对象,采取适当的措施解决它,然后再次进行原始调用。 And, I want to avoid the callback soup that my current implementation has. 而且,我想避免当前实现中的回调汤。

(bad) Javascript Example : (错误)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...
});

The trick is to set things up to run recursively. 诀窍是将事情设置为递归运行。

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);

Using this logic, the doSomethingINteresting function, and your error callbacks will call each other as many times as necessary, without you having to nest a potentially infinite number of callbacks. 使用此逻辑,doSomethingINteresting函数以及您的错误回调将在需要时相互调用多次,而不必嵌套潜在的无限数量的回调。 YUCH! CH!

There is something called the Promise pattern, it is a way to emulate synchronus behavior in async. 有一种叫做Promise模式的东西,它是一种在异步模式下模拟syncnus行为的方式。

For example, traditionally with the callback method one would write code such as this: 例如,传统上使用回调方法将编写如下代码:

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?
        });
    });
});

However using the Promises pattern, one would write: 但是,使用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();

Both code examples were taken from i2devs . 这两个代码示例均来自i2devs For more information just search for Promise Javascript Pattern. 有关更多信息,请搜索Promise Javascript Pattern。 It is too large to include here. 它太大,无法包含在此处。

Note : In terms of error handling, with the Promise pattern, if an error is thrown it is carried all the way to the .fail() method as you can see in the second example, just as you would expect in normal try/catch routines. 注意 :在错误处理方面,使用Promise模式,如果引发错误,则将其一直带到.fail()方法,如在第二个示例中看到的,就像在正常try / catch中所期望的那样例行程序。

For Promise pattern libraries I would suggest Q or bluebird 对于Promise模式库,我建议使用Qbluebird

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

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