NodeJS – 如何发送一个variables嵌套callback? (MongoDB查找查询)

我想在另一个结果集中使用find查询的结果集。 我无法用英语很好地解释这种情况。 我会尝试使用一些代码。

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

首先,我find所有find John的人。 然后我把这些人当作所有的人。

其次,我在不同的查找查询中,逐一获取每个约翰的所有宠物。

在第二次callback中,我再次获得每一个宠物。 但是当我想要展示哪个约翰是他们的主人时,我总是得到同样的约翰。

所以,问题是:我怎样才能把每个约翰单独发送给第二个嵌套的callback函数,并将它们作为真正的所有者和宠物一起使用。

我需要复制每一个约翰,但我不知道我该怎么做。

Javascript没有块范围,只有函数范围。 使用forEach将为每个循环创build一个新的作用域:

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

你必须更加注重asynchronous性。

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