I have a somewhat unreliable REST API which I'm calling (around 20% of the time it throws a 502 error). I want to be able to catch the error, then rerun the function, but after a delay. If the error occurs again I want to double the original delay and have it rerun, if it occurs again repeat those steps with the delay doubled again and so on. I think I would use a setTimeout function with the delay being a variable which changes and then clearTimeout on success. My issue is I don't know how I would implement this, and specifically I don't know how I would rerun that exact API call which threw the error. My code is below, any help is much appreciated.
Also this is for a NextJS React app if that changes anything.
const allData = async () => {
const dates = getArrayOfDates('START_DATE', 'END_DATE');
let dataStructure = {
"country_name": "",
"iso": "",
"data": {
}
}
dates.map(async (date) => {
options = {
method: 'GET',
url: 'https://covid-19-statistics.p.rapidapi.com/reports',
params: {
iso: 'USA',
date: date
},
headers: {
'x-rapidapi-host': 'covid-19-statistics.p.rapidapi.com',
'x-rapidapi-key': 'API_KEY'
}
};
let cases = 0;
let deaths = 0;
let dateV;
await axios.request(options).then(response => {
dateV = response.data.data[0].date;
const data = response.data.data;
data.map(item => {
cases += item.confirmed;
deaths += item.deaths;
});
})
.then(()=> {
console.log("DATE", dateV, "cases", cases, "deaths", deaths)
dataStructure.country_name = "US";
dataStructure.iso = "USA";
dataStructure.meta_data[dateV] = {
"cases": cases,
"deaths": deaths,
"date": dateV
}
})
.catch(error => {
console.error(error);
});
})
}