Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS async library parallel method strange behavior

NodeJS async library parallel method strange behavior

Problem

I'm attempting to use the async module with NodeJS for the first time, and I'm running into a problem when I try and dynamically construct an array of functions for the async.parallel function to run:

    methods = [];
    for (key in entries) {
      methods.push(function(callback) {
        return callback(null, key);
      });
    }
    return async.parallel(methods, function(err, results) {
      console.log(results);
      return render_views(req, res, 'view_blog_all', {
        entries: entries
      });
    });

The output I keep seeing is:

    [ 'powerful_sms_communication_for_teams',
  'powerful_sms_communication_for_teams',
  'powerful_sms_communication_for_teams' ]

And my 'entries' object I'm looping over definitely has three different keys. Something I'm missing?

ASYNC MODULE: https://github.com/caolan/async

Problem courtesy of: Casey Flynn

Solution

This is a common problem people run into with asynchronous logic. The key is to remember that your callback will not run until you call async.parallel, and at that point, key will the last key value in the loop.

One way to solve this is to capture the key value within a new scope using an IIFE.

methods = [];
for (key in entries) {
  (function(key){
    methods.push(function(callback) {
      return callback(null, key);
    });
  })(key);
}

You can also use async.map with a normal array and single iterator instead.

return async.map(
  entries,
  function(key, callback){
    callback(null, key);
  },
  function(err, results) {
    console.log(results);
    return render_views(req, res, 'view_blog_all', {
      entries: entries
    });
  }
);
Solution courtesy of: loganfsmyth

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS async library parallel method strange behavior

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×