-
-
Save EGreg/1678415 to your computer and use it in GitHub Desktop.
Asynchronous loop issues illustrative example
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
// 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