navy1978 navy1978 -5 years ago 83
Javascript Question

Download file from a different url if the others are not available

I have different urls to different servers but same file, in order to be sure that one of the above servers is alive I would like to try to download from the first, if it fails try with the second and so on....

If there a better way to do it instead of use the one I have in my mind? that is this:

var urls=["","",""]
$.get(ulrs[0]).done(function () {
}).fail(function () {
alert(" First failed!, try with second");
$.get(ulrs[1]).done(function () {
}).fail(function () {
alert("Second failed! Try with third...");
$.get(ulrs[2]).done(function () {
}).fail(function () {
alert("All failed!");

EDIT: I would like to generalize it in order to be used with different arrays with different sizes...

Answer Source

Use recursion:

function requestNext(arr, success, error) {
    if (!arr.length)
        return error();

    function onError() {
        alert(url + " failed!");
        requestNext(arr, success, error);
    var url = arr.shift();
var urls = ["","",""];
requestNext(urls, function(){ alert("success"); }, function(){ alert("all failed") });

The urls array will be mutated after this function completes. If you don't want this to happen, either pass a copy:

requestNext(urls.slice(), function(){ alert("success"); }, function(){ alert("all failed") });

Or use Dogbert's solution, change var url = arr.shift(); to:

var url = arr[0];
arr = arr.slice(1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download