1

I need to fetch data from the main service but sometimes, it's not working and I wanted to have a fallback. The idea of a Q&D solution was to download some data from it and if it fails, catch the error and change the URL to a local one. Like this.

let found = null;
try {
  $.ajax({ url: mainUrl })
    .done(function (a) { found = true; });
} catch (e) { 
  found = false;
}

In the console, I can see the browser whine about not being able to find the source but the testing variable found is still null. What am I missing?

If there's a better (but still fairly simple) way to detect the presence of the web services? If so, I'm open to suggestions. But mainly, I'm curious what's wrong with the sample above.

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

1 Answers1

2

The call is asynchronous, the browser doesn't wait for your ajax to finish before continuing onto the rest of your script (where you check the value of found for example).

Also, the try/catch isn't going to set found to false because the ajax is triggering, it's just failing on the call. Try using .fail() after your .done() to catch a failed request.

This still won't set your found variable to false, though. Have a look here for an explanation much better than I can provide on how to deal with this: https://stackoverflow.com/a/14220323/1843048

Community
  • 1
  • 1