I am using the excellent caolan “async” module for nodejs:
I have this code:
exports.manageComments = function(req, res) {
var toDeleteIds = [];
var deleteFunctions = [];
if (req.body.doDelete) {
toDeleteIds = req.body.doDelete;
}
var i;
for ( i = 0; i < toDeleteIds.length; i++ ) {
var deleteFunction = function(callback) {
var id = toDeleteIds[i];
console.log(id);
Comment.findOne({_id:id}, function(err, found) {
if (!err) found.remove(callback);
});
}
deleteFunctions.push(deleteFunction);
}
async.parallel(
deleteFunctions,
function(err,results) {
exports.comments(req, res); //render a view
}
);
};
My array contains two elements but console.log() keeps telling me “undefined”.
What am I missing?
Your problem is with:
because at the time each callback function is executed,
iwill have the same value astoDeleteIds.length. A closure doesn’t “trap” the value that an outer variable had at the time it was created; it “traps” a reference to whatever value the outer variable has at the time it’s executed (which in this case won’t be until well after yourforloop has finished.In order to “trap” the value of
iat the time you create your callback function, you need to makeia parameter of a function that you call to create your callback function. You need something likeAnd then create a separate function outside the callback: