themazz
themazz

Reputation: 1137

asyn foreach in jQuery

What I want is to run a code in asynchronous mode to get a faster response (multi-thread).

I have an array like "sources" with feeds and what I want is to get data from each one.

I've thought something like this :

$.each(sources, function(key, val) {
    JSON CALL OF EACH SOURCE
}

and then group all the results in an array and show them. The problem is that I want the json calls in asynchronous mode due to some of them take some time.

How could I do the 'each' in async mode with jQuery ??

Upvotes: 2

Views: 1939

Answers (1)

Alnitak
Alnitak

Reputation: 339786

Using deferred objects:

// get an array of jqXHR objects - the AJAX calls will
// run in parallel, subject to browser limits on the number
// of concurrent connections to each host
var defs = $.map(sources, function() {
    return $.ajax({ url: this });
});

// when they're all done, invoke this callback
$.when.apply($, defs).done(function() {
    // "arguments" array will contain the result of each AJAX call        
    ...
});

To alter the AJAX function so that only the data argument is returned, you can use .pipe():

var defs = $.map(sources, function() {
    return $.ajax({ url: this }).pipe(function(data, text, jqxhr) {
        return data;  // filtered result 
    });
});

Upvotes: 3

Related Questions