Created
November 28, 2011 13:16
-
-
Save tastapod/1400366 to your computer and use it in GitHub Desktop.
Use async module to run multiple GETs simultaneously and call a function when they are all back
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var urls = ['http://one.com', 'http://two.com'], | |
results = []; | |
async.forEach(urls, function(url, done) { | |
$.get(url, function(data) { | |
results.push(data); | |
done(); | |
}); | |
}, function(err) { | |
console.dir(results); // all results are back | |
}); |
Hi Julian. That doesn't quite work because the async callback function looks like function(err) {...}
and the $.get
callback is function(data) {...}
, so the async callback thinks it has failed as soon as the first $.get
comes back with data!
Serves me right for not testing it thoroughly... :)
Anyway, this definitely does work
<script src='https://raw.github.com/caolan/async/master/lib/async.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script>
$(function() {
var jQueryToAsync = function(f) {
return function(data, c) {
var p = f(data);
p.success(function(d) {
return c(null, d);
});
p.error(function(e) {
return c(e);
});
}
};
var urls = ['x.html', '/x.html'];
return async.map(urls, jQueryToAsync($.get), function(e, data) {
if (e) return console.error(e);
console.log(data);
});
});
</script>
I prefer this because the problem of adapting jQuery to async is isolated to one function, and you haven't got a side-effect from the result/done work. Admittedly, it's slightly longer, but the jQueryToAsync routine should work for any similar jQuery function.
Needless to say, this code is vastly easier on the eye in CoffeeScript. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you can use async.map
Apologies if this is slightly wrong, haven't got an environment handy atm.