nodejs ajax请求失败,nodejs异步请求重试策略总结

对于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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值