Skip to content

Instantly share code, notes, and snippets.

@davej
Forked from EGreg/gist:1678415
Created January 26, 2012 01:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davej/1680278 to your computer and use it in GitHub Desktop.
Save davej/1680278 to your computer and use it in GitHub Desktop.
Asynchronous loop issues illustrative example
// Illustrative case
// YEAH -- ILLUSTRATIVE OF THE FACT THAT YOU CAN ISSUE PARALLEL QUERIES TO THE DATABASE INSTEAD OF SERIAL ONES LIKE A DUMB THREADED IMPLEMENTATION THAT IS INFERIOR FOR DOING WEB SERVERS
function (recentBlogPostIds, callback) { // obviously you need this, but use callback instead of return
var results = [], // Use array not object
, len = recentBlogPostIds.length; // Cache length since we'll be using it more than once
for (var i = 0; i < len; i++) {
var blogPostId = recentBlogPostIds[i];
// var results = []; <-- RESETTING results IN THE FOR LOOP IS WRONG EVEN WITHOUT ASYNC!
function(i) { // use self-executing anonymous function to scope iteration variable
// Fetch from DB
asynchronousDB.getBlogPostById(blogPostId, function(err, blogPostId, post) {
results[blogPostId] = post;
if (i === len - 1) callback(results);
});
}(i)
}
// Return results
// return results; <-- WRONG, THE I/O HASN'T HAPPENED YET
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment