NodeJS -如何发送一个变量嵌套回调?(MongoDB查找查询)

NodeJS - how to send a variable to nested callbacks? (MongoDB find queries)

本文关键字:回调 嵌套 MongoDB 查询 查找 变量 一个 何发送 NodeJS      更新时间:2023-09-26

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

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。然后我把这些人作为allJohns

其次,我在不同的查找查询中逐个获得每个Johns的所有宠物。

在第二次回调中,我再次逐个获得每个宠物。但是当我想显示哪个John是它们的主人时,我总是得到同一个John。

那么,问题是:我如何将每个John分别发送到第二个嵌套回调,并且它们将作为真正的主人和宠物在一起。

我需要复制每个John,但是我不知道怎么做

Javascript没有块作用域,只有函数作用域。使用forEach将为每个循环创建一个新的作用域,而不是for .. in ..:

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