2013-03-05 61 views
0

首先,我在json中有一個數據數組,例如, var a = [{'name':'jack','age': 15},{ '名稱': '湯姆', '年齡':30}];在node.js中,如何在這種情況下進行異步回調

而且,我有一個基於mongodb的數據庫,它是用貓鼬來實現的。在數據庫內部,有一個用戶集合存儲用戶的其他信息。

所以現在我想查詢上面顯示的人員列表中的信息。

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

    });            
} 

我知道這是一種錯誤的獲取正確的數據,所以任何人都可以幫助我如何以異步方式編寫代碼?

+0

看看異步。 npm安裝異步https://github.com/caolan/async#each – 2013-03-05 21:12:19

+0

謝謝Hector,異步工作,但我有一個額外的要求,結果應該有與原始數組相同的序列。 async.forEach不會以這種方式工作,我也嘗試了async.eachSeries,但代碼永遠不會被執行,對我來說很陌生 – user824624 2013-03-05 22:39:24

+0

我建議在http://stackoverflow.com/questions查看我對類似查詢的回答。/13907495/how-to-ensure-that-a-statement-gets-executed-after-a-loop-completed/13920464#13920464 – cjohn 2013-03-06 00:49:38

回答

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 
} 
+1

@ user824624的評論之一提到他需要的結果與原始數組的順序相同。如果你也通過索引,例如'(函數(item,index){...})(a [i],i)' – 2013-03-06 10:38:44

+0

你對他的評論是正確的,而且可能有效。但是,如果回調的順序相同,他只能得到相同的序列。這可能是正常的行爲,但沒有保證。但是,也就是說,你的索引可以顯示他的順序。所以它是更好的;-) – heinob 2013-03-06 10:50:40

相關問題