Question:
I'm writing a promise retry function (that will retry promise on 'x' attempts).
Problem:
However, I am not able to understand why
.catch()
block is not getting invoked. It complains that there's no catch block (even though I have one)How do I make sure the catch block is invoked?
This is my code:
// This function waits for 'timeout'ms before resolving itself.
function wait(timeout) {
return new Promise((resolve, reject) => {
setTimeout(function() {
resolve();
}, timeout)
});
}
// Library function to retry promise.
function retryPromise(limit, fn, timeout=1000) {
return new Promise((resolve, reject) => {
fn().then(function(val) {
return resolve(val);
}, function(err) {
if(limit === 0) return reject('boom finally');
console.log("Retrying Promise for attempt", limit);
wait(timeout).then(() => retryPromise(limit-1, fn, timeout));
})
});
}
// Caller
const print = retryPromise(3, demo);
print.then(function(result) {
console.log(result);
}).catch(function(err){
console.log('Inside catch block');
console.error("Something went wrong", err);
});
function demo(val) {
return new Promise((resolve, reject) => {
setTimeout(function() {
return reject(val || 1000);
}, 1000);
});
}
What am I missing in the code? Please elucidate.