实现:ajax请求超时重连,但超过最大重连次数即停止重连
// 模拟ajax请求
function ajaxFn(resolve, reject){
var random = Math.random() * 10;
setTimeout(()=>{
if(random > 9){
resolve('成功了:' + random)
}else{
reject('失败了:' + random)
}
}, random)
}
/**
* promise轮询函数封装 处理ajaxFunc
* @param {funtion} ajaxFunc 需要处理的函数
* @param {number} times 最大重连次数,默认3次
* @param {number} cur 当前连接次数
*/
function maxPolling(ajaxFunc, times = 3, cur = 1){
console.log('第'+ cur +'次连接了!')
return new Promise(function(resolve, reject){
ajaxFunc(resolve, reject);
}).then(res=>{
return res;
}, err=>{
if(cur >= times){
return err
}else{
return maxPolling(ajaxFunc, times, cur + 1);
}
});
}
maxPolling(ajaxFn).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
});