[英]NodeJS - how to send a variable to nested callbacks? (MongoDB find queries)
我想在另一個結果集中使用查找查詢的結果集。 我無法用英語很好地解釋這種情況。 我會嘗試使用一些代碼。
People.find( { name: 'John'}, function( error, allJohns ){
for( var i in allJohns ){
var currentJohn = allJohns[i];
Animals.find( { name: allJohns[i].petName }, allJohnsPets ){
var t = 1;
for( var j in allJohnsPets ){
console.log( "PET NUMBER ", t, " = " currentJohn.name, currentJohn.surname, allJohnsPets[j].name );
t++;
}
}
}
});
首先,我找到所有找到名叫約翰的人。 然后我把那些人當作所有的約翰 。
其次,我由一個不同的發現查詢得到的每一個約翰斯所有的寵物。
在第二次回調中,我再一次得到每只寵物。 但是當我想要顯示哪個約翰是他們的主人時,我總是得到同樣的約翰。
所以,問題是:如何將每個John分別發送給第二個嵌套回調,他們將作為真正的所有者和寵物聚集在一起。
我需要復制每個約翰,但我不知道我怎么能這樣做。
Javascript沒有塊范圍,只有函數范圍。 而不是for .. in ..
,使用forEach
將為每個循環創建一個新的范圍:
People.find( { name: 'John'}, function( error, allJohns ){
allJohns.forEach(function(currentJohn) {
Animals.find( { name: currentJohn.petName }, function(err, allJohnsPets) {
allJohnsPets.forEach(function(pet, t) {
console.log( "PET NUMBER ", t + 1, " = ", currentJohn.name, currentJohn.surname, pet.name );
});
});
});
});
你必須更加專注於異步性質。
People.find( { name: 'John'}, function( error, allJohns ){
for( var i=0; i<allJohns.length; i++ ){
(function(currJohn){
var currentJohn = currJohn;
Animals.find( { name: currentJohn.petName }, function(error, allJohnsPets){
for(var j=0; j<allJohnsPets.length; j++){
console.log( "PET NUMBER ", (j+1), " = " currentJohn.name, currentJohn.surname, allJohnsPets[j].name );
}
})
})(allJohns[i]);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.