Skip to content

Instantly share code, notes, and snippets.

@EGreg
Forked from fennb/gist:1124580
Created January 25, 2012 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save EGreg/1678415 to your computer and use it in GitHub Desktop.
Save EGreg/1678415 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 = {};
var count = 0;
for (var i = 0; i < recentBlogPostIds.length; i++) {
var blogPostId = recentBlogPostIds[i];
// var results = []; <-- RESETTING results IN THE FOR LOOP IS WRONG EVEN WITHOUT ASYNC!
// Fetch from DB
asynchronousDB.getBlogPostById(blogPostId, function(err, blogPostId, post) {
results[blogPostId] = post;
if (++count === recentBlogPostIds.length) callback(results);
});
}
// 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