I am trying to fetch data from an array of URLs using the fetch()
request method:
const urls = [
'https://dewnuf111111.com/configuration',
'https://dewnuf222222.com/configuration',
'https://bcsmania.co.uk/test.json'
];
In case there is an error during the fetch (such as site not found or internal server error), I want the script to try the next URL in the array. To achieve this, I have included a counter variable. Once it successfully fetches data from a working URL, it should log 'DONE' to the console. However, my current implementation seems to have some issues.
This is the code snippet I have been working on:
const urls = [
'https://dewnuf111111.com/configuration',
'https://dewnuf222222.com/configuration',
'https://bcsmania.co.uk/test.json'
];
let obj = {a: 'test'};
let counter = 0;
function ajax(url) {
// Check for last URL in the array
if (counter < urls.length) {
return fetch(url)
.then(response => {
// Merge response with object
obj = Object.assign(obj, response.json());
console.log(urls[counter], obj);
return Promise.resolve(obj);
}).catch(error => {
counter++;
// Try fetching the next URL
ajax(urls[counter]);
});
}
}
function getConfigurations() {
return ajax(urls[counter]);
}
getConfigurations().then((configurations) => {
console.log('DONE', configurations);
});
You can view a preview of the script on JSFiddle.
I'm seeking guidance on where I might be making mistakes. Should I consider making the function async
and using await
for better results?