I am using fetch API and try to implement a function which gets retry parameter and re-sends another request if the previous one was failed. I've found this answer and here is my code, Does anybody know how to write the function in none-recursion?
const fetchRetry = (url, delay, limit, fetchOptions = {}) => {
return new Promise((resolve, reject) => {
const success = (response) => resolve(response);
const failure = (error) => {
if (limit) {
setTimeout(fetchUrl, delay)
}
else {
// this time it failed for real
reject(error);
}
limit--;
}
const finalHandler = (finalError) => { throw finalError };
const fetchUrl = () => {
return fetch(url, fetchOptions)
.then(success)
.catch(failure)
.catch(finalHandler);
}
fetchUrl();
});
}
fetchRetry('https://jsonplaceholder.typicode.commmmmm/posts/1', 1000, 3)
.then((response) => {
if (!response.ok) {
throw new Error('failed!');
}
return response;
})
.then((response) => console.log(response))
.catch((error) => console.log(error));