首先,我在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);
});
}
我知道這是一種錯誤的獲取正確的數據,所以任何人都可以幫助我如何以異步方式編寫代碼?
看看異步。 npm安裝異步https://github.com/caolan/async#each – 2013-03-05 21:12:19
謝謝Hector,異步工作,但我有一個額外的要求,結果應該有與原始數組相同的序列。 async.forEach不會以這種方式工作,我也嘗試了async.eachSeries,但代碼永遠不會被執行,對我來說很陌生 – user824624 2013-03-05 22:39:24
我建議在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