Arlen Beiler
Arlen Beiler

Reputation: 15876

Asynchronous IO and iteration variables in Javascript

I am working with NodeJS and MongoDB and on start I create collections and fill them in if they don't already exist. Right now this is just development , but with backups and things I could end up doing the same thing or something similar in production.

My question is what will happen to the iteration variable(i)? Will the callback use the correct value for that iteration? Or will it get some other value further down the list, or perhaps none at all?

ldb.createCollection('people', { strict: true }, function(err, col){
    if(err) { console.log('createCollection( people ) ', err); } 
    else { 
        for(var i in people){
            col.insert(people[i], { w: 1 }, function(err, doc){
                people[i]._id = doc._id;
            }
        }
    }
});

Edit: This is an object, not an array.

Upvotes: 0

Views: 36

Answers (1)

SimpleJ
SimpleJ

Reputation: 14768

When the callback passed into insert is called, the value of i will not be preserved (it will most likely be the last key in people). If you want to preserve i, you could give it its own functional scope like this:

people.forEach(function(person, i) {
    col.insert(person, { w: 1 }, function(err, doc) {
        person._id = doc._id;
    });
});

edit: Using an anonymous function instead of the forEach method:

for(var i in people) {
    function(i) {
        col.insert(people[i], { w: 1 }, function(err, doc){
            people[i]._id = doc._id;
        });
    }(i);
}

Upvotes: 1

Related Questions