简体   繁体   中英

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM