2

I have some function like this...

for(key in object){
    db.collection.findOne(criteria, function(err, doc){
        // ...
        db.collection.update(...);
    })
};

However, the value of key changes before the mongodb calls are complete, i.e. the loop goes into next iteration. Is there a way to do it in sequential manner. Or is there something for objects like async.map() for arrays?

2 Answers 2

3

All the calls to your callback will happen after all the iterations of the loop have taken place, so when they get executed the value of key will be whatever is its last value.

One common solution is to wrap all your calls in a closure:

for(key in object){
    (function(key, value) {
        db.collection.findOne(criteria, function(err, doc){
            // ...
            db.collection.insert(...);
        })
    })(key, object[key]);
};

Another way you could achieve the same thing is to use the Object.keys() method (which creates an array out of the keys in your object) and call Array#forEach on the array. That way you can skip the extra closure because forEach already has a function callback:

Object.keys(object).forEach(function(key) {
    db.collection.findOne(criteria, function(err, doc){
        // ...
        db.collection.update(...);
    })
});

Which is arguably a bit more elegant

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Went with the Object.keys() option!
1

You could build up a closure to save the value of key

for(key in object){
  (function(ky) { 
    db.collection.findOne(criteria, function(err, doc){
        // ...
        db.collection.insert(...);
    })
  })(key)
};

2 Comments

It's called a "closure". Clojure is a programming language :)
oops, been writing too much clojure lately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.