Skip to content

Instantly share code, notes, and snippets.

@vivekteega
Last active October 25, 2019 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vivekteega/4a7e1d640e84844438fa282b0da00c17 to your computer and use it in GitHub Desktop.
Save vivekteega/4a7e1d640e84844438fa282b0da00c17 to your computer and use it in GitHub Desktop.
Fetching data from multiple backup apis
<html>
<body>
<script>
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var serverlist = ['https://explorer.mediciland.com/', 'https://livenet.flocha.in/', 'https://flosight.duckdns.org/', 'http://livenet-explorer.floexperiments.com', 'http://ec2-13-233-133-128.ap-south-1.compute.amazonaws.com/', 'http://ec2-13-233-131-136.ap-south-1.compute.amazonaws.com/', 'http://ec2-13-233-194-1.ap-south-1.compute.amazonaws.com/'];
var apicall = 'api/block-index/3719266';
var tempserverlist = serverlist;
var countervar = serverlist.length-1;
function fetch_retry(servernameposition, apicall) {
return new Promise(function (resolve, reject) { // <--- we know it is asynchronous, so just return a promise first!
fetch(tempserverlist[servernameposition] + apicall)
.then(function (result) {
/* on success */
if (result.status == 200) {
console.log('Fetch succeeded for ' + tempserverlist[servernameposition] + apicall);
result.json().then(function (data) {
console.log(data);
});
}
else {
console.log('Fetch failed for ' + tempserverlist[servernameposition] + apicall);
if (countervar === 0) return reject(error); // <--- base case!
tempserverlist.splice(servernameposition, 1);
currentFlosightPosition = getRandomInt(0,tempserverlist.length);
countervar-=countervar;
fetch_retry(currentFlosightPosition, apicall)
.then(resolve)
.catch(reject);
}
})
.catch(function (error) {
console.log('Fetch failed for ' + tempserverlist[servernameposition] + apicall);
if (countervar === 0) return reject(error); // <--- base case!
tempserverlist.splice(servernameposition, 1);
currentFlosightPosition = getRandomInt(0,tempserverlist.length);
countervar-=countervar;
fetch_retry(currentFlosightPosition, apicall)
.then(resolve)
.catch(reject);
})
});
}
var currentFlosightPosition = getRandomInt(0,serverlist.length);
fetch_retry(currentFlosightPosition, apicall);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment