在node.js中,如何在这种情况下进行异步回调

时间:2013-03-05 20:40:15

标签: node.js callback mongoose

首先,我在json中有一个数据数组,例如, var a = [{'name':'jack','age':15},{'name':'tom','age':30}];

而且,我有一个基于mongodb的数据库,它是用mongoose实现的。在数据库内部,有一个存储用户其他信息的用户集合。

现在,我想在上面显示的人员列表中查询信息。

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 );

    });                                             
}

我知道获取正确的数据是错误的,所以任何人都可以帮助我以异步方式编写代码吗?

1 个答案:

答案 0 :(得分:2)

您必须将函数置于闭包中并将相关变量作为参数推送到其中:

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
}