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
themazz
1,1373 gold badges10 silver badges29 bronze badges
-
see this bennadel.com/blog/…andres descalzo– andres descalzo2012年10月25日 00:42:57 +00:00Commented Oct 25, 2012 at 0:42
1 Answer 1
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
Alnitak
341k72 gold badges420 silver badges503 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
themazz
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
Alnitak
@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]Alnitak
@themazz there's a way to simplify this - I'll edit the answer
themazz
Thank you, your solution gave me an outstanding improvement to my system !
Alnitak
@themazz glad to have helped :)
lang-js