2

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 ??

asked Oct 24, 2012 at 22:46
1

1 Answer 1

3

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 
 });
});
answered Oct 24, 2012 at 22:50
Sign up to request clarification or add additional context in comments.

5 Comments

Doing this : $.when.apply(,ドル defs).done(function(data) { console.log(data); I get something like this: [ Array[88] , "success", Object ] The data is in that array[88], but how could I access to it ?? Sorry for this but Im struggling with this and the answer must be easy
@themazz you'll get one such entry for each AJAX call - use the arguments pseudo-array (per the code) to access them. Ah, I see, each element also contains the AJAX textStatus and jqXHR result too. So to access the nth set of data, use arguments[n][0]
@themazz there's a way to simplify this - I'll edit the answer
Thank you, your solution gave me an outstanding improvement to my system !
@themazz glad to have helped :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.