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

What is the variable scope for async tasks?

What is the variable scope for async tasks?

Problem

var itemIds, result, taskQueue, _i, _len;
itemIds = [];
taskQueue = async.queue(function(task, callback) {
  console.log('Hello ' + task.name);
  return callback();
}, 10);
for (_i = 0, _len = results.length; _i 

is my code. But itemIds shows as empty when the drain is run. This is using the async module for node.js by the way

Problem courtesy of: Shamoon

Solution

I'd personally recommend you heavily simplify the code using after

var slice = Array.prototype.slice;

var cb = after(results.length, function() {
    var items = slice.call(arguments);
    console.log("All done");
    console.log(items.length);
});

results.forEach(function(result) {
    item = new Item(result);
    item.save(function(err, newItem) {
        cb(newItem);   
    }); 
});
Solution courtesy of: Raynos

Discussion

View additional discussion.



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

Share the post

What is the variable scope for async tasks?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×