Javascript fetch api is a great tool to make rest request. It is very easy to use and it is supported by all modern browsers. But sometimes we need to retry the request if it fails. In this post we will see how to retry the request if it fails.
Fetch usages without retry
Let’s see how to use fetch api to make a rest request. We will use the fake api to make the request
We will use the following code to make the request.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
Fetch usages with retry
Now we will see how to retry the request if it fails. We will use the following code to retry the request.
const retry = (fn, retriesLeft = 5, interval = 1000) => {
return new Promise((resolve, reject) => {
fn()
.then(resolve)
.catch(error => {
setTimeout(() => {
if (retriesLeft === 1) {
// reject('maximum retries exceeded');
reject(error);
return;
}
// Passing on "reject" is the important part
retry(fn, retriesLeft - 1, interval).then(resolve, reject);
}, interval);
});
});
};
retry(() => fetch('https://jsonplaceholder.typicode.com/todos/1'))
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));
The above code will retry the request if it fails. The retry function will take three parameters. The first parameter is the function to retry. The second parameter is the number of retries. The third parameter is the interval between retries. The retry function will return a promise. The promise will resolve if the request is successful. The promise will reject if the request fails after the maximum retries.
It will retry the request 5 times with an interval of 1 second. If the request fails after 5 retries then the promise will reject with the error. The error will be printed in the console.