user824624
user824624

Reputation: 8068

In node.js, how do I make a asynchronous callback in this situation

Firstly, I have a array of data in json, for example, var a = [{'name':'jack','age':15},{'name':'tom','age':30}];

And what is more, I have a mongodb based database, which is implemented in mongoose. Inside the database, there is a user collection storing user's other information.

So right now, I want to query the information in a list of people shown above.

for(var i=0;i<a.length;i++){
    console.log('time schedule '+"   "+a[i].name+"   "+a[i].age);                               
    model.findOther(a[i].name,function(err,data){ 
        // I can get the data from mongodb  
          console.log("time schedule data:"+"   "+data.otherinfo+"  ");
       --------------------------------------------------------------------------------
       //however the problem arises that I can not get the a[i].age inside the callback
          console.log(a[i].age );

    });                                             
}

I know it is kind of wrong to get the right data, so could anyone help me how to write the code in asynchronous way?

Upvotes: 0

Views: 139

Answers (1)

heinob
heinob

Reputation: 19464

You have to put your function into a closure and push the related variable as a parameter into it:

for(var i=0;i<a.length;i++){
    console.log('time schedule '+"   "+a[i].name+"   "+ai].age);
    (function(item){
        model.findOther(item.name,function(err,data){ // <-- here you could use 'a[i]' instead of 'item' also
            console.log("time schedule data:"+"   "+data.otherinfo+"  ");
            console.log(item.age );  // <-- here you must use 'item'
        });
    }(a[i])); // <-- this is the parameter of the closure
}

Upvotes: 2

Related Questions