Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first available data source with jQuery Deferred

So I was asked this at an interview, but it brought up a good use case. Assume that you have a bunch of data sources. You want to find the first available one and process it and ignore the rest.

So something like:

var datasources = new Array("somedatabase1/pizza","somedatabase2/beer","somedatabase3/llama");
var dfds = new Array();
$.each(datasources,function(source){
    dfds.push($.getJSON(source));
});

$.when(dfds).done(function(){alert("they are all done");});

Ignore that I really don't think when accepts an array (maybe it does). This of course would make it wait till they are all completed. I am looking for some code that would make it wait until one, any of them is done, and then not worry about the others.

I was informed that it would only work recursively.

like image 450
Parris Avatar asked Oct 08 '22 12:10

Parris


1 Answers

This doesn't use recursion but fits the requirement to fetch from multiple datasources and only care about the first that returns a successful response.

http://jsfiddle.net/mNJ6D/

function raceToIt(urls) {
    var deferred = $.Deferred(),
        promises;

    function anyComplete(data) {
        if (!deferred.isResolved()) {
            deferred.resolveWith(this, [data]);
            promises.forEach(function(promise) {
                promise.abort();
            });
        }
    }
    promises = urls.map(function(url) {
        return $.getJSON(url).then(anyComplete);
    });
    return deferred.promise();
}
raceToIt(["/echo/json/", "/echo/json/", "/echo/json/"]).then(function(data) {
    console.log(data);
});​
like image 102
Esailija Avatar answered Oct 10 '22 10:10

Esailija