Retry Promises
Implement a function in JavaScript that retries promises N number of times with a delay between each call.
const wait = (delay) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, delay);
});
};
const testPromise = (n) => {
let count = 0;
return () => {
return new Promise((resolve, reject) => {
count += 1;
if (count <= n) {
reject("Failed the try");
} else {
resolve("Succeed the try");
}
});
};
};
const retry = (
fn,
retries,
delay = 1000,
finalError = "Failed all retries"
) => {
return new Promise((resolve, reject) => {
fn()
.then((res) => {
resolve(res);
})
.catch((err) => {
console.log(err);
if (retries === 1) {
return reject(finalError);
}
wait(delay).then(() => {
return retry(fn, retries - 1, delay, finalError).then(
resolve,
reject
);
});
});
});
};
retry(testPromise(5), 5)
.then((res) => console.log(res))
.catch((err) => console.log(err));
// Failed the try
// Failed the try
// Failed the try
// Failed the try
// Failed the try
// Failed all retries
retry(testPromise(5), 6)
.then((res) => console.log(res))
.catch((err) => console.log(err));
// Failed the try
// Failed the try
// Failed the try
// Failed the try
// Failed the try
// Succeed the try
Retry Promises in Async Await
const wait = (delay) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, delay);
});
};
const testPromise = (n) => {
let count = 0;
return async () => {
count += 1;
if (count <= n) {
throw new Error("Failed the try");
} else {
return Promise.resolve("Succeed the try");
}
};
};
const retry = async (
fn,
retries,
delay = 1000,
finalError = "Failed all retries"
) => {
try {
const response = await fn();
return response;
} catch (err) {
console.log(err.message);
if (retries == 1) {
return Promise.reject(finalError);
}
await wait(delay);
return retry(fn, retries - 1, delay, finalError);
}
};
const test1 = async () => {
try {
const response = await retry(testPromise(5), 5);
console.log(response);
} catch (err) {
console.log(err);
}
};
test1();
// Failed the try
// Failed the try
// Failed the try
// Failed the try
// Failed the try
// Failed all retries
const test2 = async () => {
try {
const response = await retry(testPromise(5), 6);
console.log(response);
} catch (err) {
console.log(err);
}
};
test2();
// Failed the try
// Failed the try
// Failed the try
// Failed the try
// Failed the try
// Succeed the try