public
Created — forked from fennb/gist:1124580

Asynchronous loop issues illustrative example

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// 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
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.