Have you run into a situation when you needed to call a buggy API that responds with an error ever so often?
What's the solution if you have no control over that API?
Retries to the rescue!
As it happens...
- Our
fetchDataWithRetries
function takes in the maxReties (uses 3 as a default value) - When called, this function returns a function and we make use of closure to capture the value of
tries
andmaxTries
- The returned function -
apicall
- takes in the URL to be called.- If the response is a success - return it as is
- If there's an error increment the tries, check for max retry limit and recursively call itself
const fetch = require('node-fetch');
function fetchDataWithRetries(maxTries) {
maxTries = parseInt(maxTries);
if(!maxTries) maxTries = 3;
let tries = 0;
return function apicall(url) {
if (!url) return Promise.reject("URL required")
console.log("APICALL " + (tries + 1));
return fetch(url)
.then(function (res) {
console.log("fetch success");
return res.json();
})
.catch(e => {
console.log("Fetch Error")
if (++tries < maxTries)
return apicall(url);
return Promise.reject(e)
});
}
}
const retyCount = 2, APIURL = 'https://jsonplaceholder.typicode.com/users/1';
fetchDataWithRetries(retyCount)(APIURL)
.then(data => console.log(data))
.catch(err => console.log(err));
Top comments (2)
Great simple explanation, just add "url" when run "apicall" in catch fetch.
Thanks for the read. Updated.