Node.js-错误回调的重新调用功能-是否有非阻塞方式? [英] Nodejs - Re-Calling function on error callback - Is there a non blocking way?

查看:97
本文介绍了Node.js-错误回调的重新调用功能-是否有非阻塞方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向API发出请求的函数。有时,API偶尔会打h,一两秒钟都无法使用,导致出现错误,我想再次调用该函数。由于此回调之后还有70〜80行代码,因此我不想使用 if(error)< do the same stuff>拆分流。其他<如此处>

I got a function which makes a request to an API. Sometimes the API got some hiccups and isnt available for a second or two every now and then, resulting in an error on which I'd like to call the function again. Since there are another 70~80 lines of code following this callback, I wouldnt like to split the flow with an if(error) <do the same stuff> else <as here>

尝试了一段时间后,我最终使用了一个do-while(error)循环,该循环有效,但块。有异步的方法吗?

After trying for quite some time I ended up using a do-while(error) loop, which works but blocks. Is there an async way of doing this?

我的代码(为通用化而简化):

My code (simplified for generalization):

//This is the request part

function bar(j, callback){      
   j++;

   //simulated error
   if(j<=10){   
       return( callback('dont', j) );
   }
   //simulated success
   else{
       return( callback(null, j) );
   }

}

//This is the main function - part of a bigger piece in my code

function foo(){
   var i = 0;
   var err = 'yes'; //else we'd get an 'err is not defined'

   do{
     bar(i, function(error, j){
        i = j
        err = error;

        if(error){
          console.log(i); 
        }
        else{       
          return( console.log('done it!') );    
          // There's more here in my code
        }
     });
   } while (err);

   console.log('I blocked');
}

foo();

编辑:

对于那些感兴趣的人,这是输出:

For those interested, this is the output:

1

2

3

4

5

6

7

8

9

10

done it!

I blocked


推荐答案

我建议您为您的操作创建一个函数。如果失败,则设置一个短计时器,然后在计时器触发后重试。

What I would suggest is that you make a function for your operation. If it fails, you set a short timer and retry after that timer fires. This will give you an asynchronous behavior between retries and other code in the sever can run.

function requestRetry(url, data, retryTimes, retryDelay, callback) {
    var cntr = 0;

    function run() {
        // try your async operation
        request(..., function(err, data) {
            ++cntr;
            if (err) {
                if (cntr >= retryTimes) {
                    // if it fails too many times, just send the error out
                    callback(err);
                } else {
                    // try again after a delay
                    setTimeout(run, retryDelay);
                }
            } else {
                // success, send the data out
                callback(null, data);
            }
        });
    }
    // start our first request
    run();
}


requestRetry(someUrl, someData, 10, 500, function(err, data) {
    if (err) {
        // still failed after 10 retries
    } else {
        // got successful result here
    }
});

这是一个非常简单的重试方案,它仅以固定的间隔重试固定的次数。更复杂的方案实现了一种退避算法,该算法从相当快的重试开始,但是在最初的几次失败之后,退避到重试之间的较长时间,以使服务器有更好的恢复机会。如果碰巧有很多客户都在进行快速重试,那么一旦服务器出现故障,您就会遇到雪崩故障,因为所有客户端突然开始快速重试,这会使您的服务更加难以尝试处理所有这些请求。退避算法旨在使服务器有更好的机会防止雪崩故障并使其更容易恢复。

This is a fairly simple retry scheme, it just retries on a fixed interval for a fixed number of times. More complicated schemes implement a back-off algorithm where they start with fairly quick retries, but then back-off to a longer period of time between retries after the first few failures to gives the server a better chance of recovering. If there happening to be lots and lots of clients all doing rapid retries, then you as soon as your server has a hiccup, you can get an avalanche failure as all the clients suddenly start rapidly retrying which just puts your serve in even more trouble trying to handle all those requests. The back-off algorithm is designed to allow a server a better chance of preventing an avalanche failure and make it easier for it to recover.

退避方案也是如果您在等待该服务一段时间后重新上线,则更合适。

The back-off scheme is also more appropriate if you're waiting for the service to come back online after it's been down a little while.

这篇关于Node.js-错误回调的重新调用功能-是否有非阻塞方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆