Skip to content

Instantly share code, notes, and snippets.

@tastapod
Created November 28, 2011 13:16
Show Gist options
  • Save tastapod/1400366 to your computer and use it in GitHub Desktop.
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
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
});
@JulianBirch
Copy link

I think you can use async.map

var urls = ['http://one.com', 'http://two.com'];

async.forEach(urls, $.get, function(err, results) {
    console.dir(results); // all results are back
});

Apologies if this is slightly wrong, haven't got an environment handy atm.

@tastapod
Copy link
Author

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!

@JulianBirch
Copy link

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