[英]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.