实现一个promise.retry
1,描述实现一个Promise.retry 函数,使得某个函数执行得结果如果是失败请求一定的次数之后再reject,失败后间隔某个时间段之后重试,尝试超过一定次数才真正的 reject
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | /* *用随机数模拟数据数据请求 */ function getRandom(){ return new Promise((resolve, reject) => { let data = Math.random() * 10; if(data > 5){ resolve(data) }else{ reject(data) } }) } Promise.retry = function(fn, time, delay){ return new Promise((resolve, reject) =>{ let index = 0; let action = function(){ fn().then(res => { console.log("第"+index +"次请求"); console.log("成功了当前值是" + res ); }).catch(err =>{ if(time == 0){ reject(err) }else{ time--; index++; console.log("第"+index +"次请求"); console.log(err); setTimeout(() => { action() }, delay); } }) } action(resolve, reject) }) } |