JSFiddle - React, Tailwind, and code Playground
by jimyu
JavaScript
var retried = 0;
const total = 3;
function test() {
const promise = new Promise((resolve, reject) => {
var rand = Math.random();
if (rand < 0.8) {
reject(rand);
} else {
resolve(rand);
}
});
return promise;
}
function keepTrying(promise) {
promise = promise||new Promise(resolve=>{
test().then(result=>{
console.log('found ', result);
promise.resolve(result);
})
.catch(err=>setTimeout(()=>{
console.log('retrying...');
keepTrying(promise);
}, 1000));
});
// try doing the important thing
/*
if(success) {
promise.resolve(result);
} else {
setTimeout(function() {
keepTrying(otherArgs, promise);
}, retryInterval);
} */
return promise;
}
const retry = (fn, ms=1000,maxRetries=3) => new Promise((resolve,reject) => {
fn()
.then(result=>resolve(result))
.catch(() => {
setTimeout(() => {
++retried;
console.log('retrying failed promise...', retried);
if(retried<maxRetries) {
retry(fn, ms).then(result=>resolve(result));
} else {
return resolve('maximum retries exceeded');
}
}, ms);
})
});
/* const result = retry(test, 1000);
*/
var result=retry(test);
result.then(function(data) {
console.log(data);
});