I'm trying to create a generic "retry" function that accepts a promise object and plays the promise back a certain number of times before eventually resolving or rejecting.
I've already written a piece of code that accepts an array of promises and works through them sequentially until 1 succeeds or they all fail.
var first = function(promiseArr){
return promiseArr.reduce(function (prev, next) {
return prev.catch(()=>next)
});
};
first([Promise.reject("1"), Promise.resolve("2"), Promise.reject("3")])
.then(function(data){
console.log('resolved with '+data);
}, function(err){
console.log('rejected with '+err);
});
I'm now trying to write a function which accepts a promise and populates an array with size N with deep copy clones of the promise. I've managed to make it work with vanilla objects, but I can't seem to make it work with promise objects.
I realize I could just accept an executing function and build the promises myself, but I would like to be able to reuse my already promisified functions in the project.
var retry = function(promise, maxCount){
return first(Array(maxCount).fill(function(){
//return a deep copy of the promise passed in
})
}
Your approach of creating "deep clones" of a promise, whatever that is supposed to mean, and playing through them, is flawed. The paradigm for retrying a promise is nothing more complicated than
function foo() {
return doSomething().catch(foo);
}
Then you add logic for number of retries:
function retry(n) {
return function foo() {
if (!n--) return Promise.reject("max retries exceeded");
return doSomething.catch(foo);
}();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With