对于node开发同学经常要处理异步请求,然后根据请求的结果或请求成功后的状态码做不同的策略处理,众多策略中最常用的一种就是重试策略。针对重试策略我们往往还需要设定一定的规则,如重试次数、重试时间间隔、总体超时时间、重试判定等。针对以上问题,这里推荐一个工具包:bluebird-retry。
bluebird-retry基本用法如下:
var retry = require('bluebird-retry');
function logFail() {
console.log(new Date().toISOString());
throw new Error('bail');
}
retry(logFail, { max_tries: 4, interval: 500 });
结果如下:
2014-05-29T23:16:28.941Z
2014-05-29T23:16:29.445Z
2014-05-29T23:16:29.946Z
2014-05-29T23:16:30.447Z
Error: operation timed out
以上代码逻辑是,如果logFail函数报出异常或出错,则重试四次,每次间隔500毫秒。
bluebird-retry除了能够捕获异常外,还支持promise形式:
var Promise = require('bluebird');
var retry = require('bluebird-retry');
var count = 0;
function myfunc() {
console.log('myfunc called ' + (++count) + ' times');
if (count < 3) {
return Promise.reject(new Error('fail the first two times'));
} else {
return Promise.resolve('succeed the third time');
}
}
retry(myfunc)
.then(function(result) {
console.log(result);
});
最终结果:
myfunc called 1 times
myfunc called 2 times
myfunc called 3 times
succeed the third time
他对promise的支持就为我们的异步请求处理打开了大门,我们可以将bluebird,request,bluebird-retry