navy1978 navy1978 - 5 months ago 13
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=["http://Url1.com","http://Url2.com","http://Url3.com"]
$.get(ulrs[0]).done(function () {
alert("success");
}).fail(function () {
alert(" First failed!, try with second");
$.get(ulrs[1]).done(function () {
alert("success");
}).fail(function () {
alert("Second failed! Try with third...");
$.get(ulrs[2]).done(function () {
alert("success");
}).fail(function () {
alert("All failed!");
});
});
});


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

Answer

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();
    $.get(url).done(success).fail(onError);
}
var urls = ["http://Url1.com","http://Url2.com","http://Url3.com"];
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);