My app makes a fetch to a web service that can sometimes be slow to respond due to circumstances out of my control. It seems that if it gets stuck waiting for a response, the solution is to fetch for the data again. How would one make a function to fetch fetch for data every 10 seconds, and stop when the endpoint delivers a result?
Asked
Active
Viewed 849 times
-1
-
Learn `Promises` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Marko Savic May 13 '19 at 13:42
-
This looks like a good use case for using observables. – AdityaParab May 13 '19 at 13:43
-
Given the amount of detail in your question, how can you expect any more detail in an answer? As can be seen, all you'll end up with is a bunch of confusing suggestions that may (but most likely will not) be of use. Show us what you've tried when attempting to solve your question, and where ***specifically*** you've come unstuck. Vaguely asking for suggestions on SO will simply encourage down/close-votes. – spender May 13 '19 at 13:43
-
Dupe: https://stackoverflow.com/questions/46175660/fetch-retry-request-on-failure – spender May 13 '19 at 13:49
2 Answers
0
In plain JavaScript you can use setInterval
var myInterval = setInterval(tryToGetData, 10000); // Try to get data every 10 secs
function tryToGetData() {
// Get your data here, preferably as a promise
yourDataPromise.then((data) => {
clearInterval(myInterval); // Stop trying to get data every 10 secs
// Do stuff with
});
}
However a much better way is to retry the promise when it naturally fails, by trying to get the data again by catching the promise itself.

Bradd
- 196
- 10
-
Without cancelling the previous attempt to "fetch" the data, this promises to be a confusing mess. – spender May 13 '19 at 14:04
0
You need to set a timer that will fetch data every 10 seconds and if the data is found, you will clear the timer so that data will not be fetch again
var data = setInterval(function(){
// call fetch data function
fetchData((err, data) => {
if(data) {
clearInterval(data);
}
})
}, 10000);
function fetchData(cb) {
// rightnow we are passing data '1' to the callback so the timer will run only once as data is fetched
// try removing '1' and you will see that `fetchData` function is called on every 10 seconds
cb(null, 1);
}

Gaurav Umrani
- 124
- 4
- 12
-
Supposing the previous attempt completes after 11 seconds? You didn't make any attempt to cancel it. – spender May 13 '19 at 14:05
-
you can cancel the existing fetchData request before it fetches the data again cancelExistingRequest(); fetchData((err, data) => { if(data) { clearInterval(data); } }) – Gaurav Umrani May 13 '19 at 14:46