如何在node.js中使用async

时间:2016-08-23 14:26:46

标签: arrays node.js mongodb asynchronous

我在node.js中创建了一个使用mongoDB的代码。一切都运行正常,但是当我使用嵌套循环时,它会中断并且不会返回正确的值。

DB1.find({},function(error,fetchAllDB1) {
    var mainArray = new Array();
    for (var i in fetchAllDB1) {
        if(fetchAllDB1[i].name) {
            var array1  = new Array();
            var array2  = new Array();

            array1['name'] = fetchAllDB1[i].name;
            array1['logo'] = fetchAllDB1[i].logo;
            array1['desc'] = fetchAllDB1[i].desc;    

            DB2.find({is_featured:'1', brand_id: fetchAllDB1[i]._id}, function(error,fetchDB2) {
                for (var p in fetchDB2) {
                    var pArr=[];
                    pArr['_id']    = fetchDB2[p]._id;
                    pArr['name']   = fetchDB2[p].name;
                    pArr['sku']    = fetchDB2[p].sku;
                    pArr['description'] = fetchDB2[p].description;

                    console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
                    console.log(pArr);
                    console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
                    array2[p]=pArr;
                } 
                array1['pp']= array2;
            });
            mainArray[i]=array1;
        }
    }
    console.log('######### LAST #########');
    console.log(mainArray);
    console.log('######### LAST #########');
});

在我的控制台消息中显示

 console.log('######### LAST #########');

  All Values

  console.log('######### LAST #########');

之后

console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
All Values;
console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');

我想在我的代码中使用async,以便所有数据获取如下所示:

mainarray =
[
    [array1] = All Values
    [array2] = [0]
               [1]  
]

mainarray =
[
    [array1] = All Values
    [array2] = [0]
               [1]  
]

1 个答案:

答案 0 :(得分:-1)

您的代码非常混乱且过于复杂。

你应该做的是(伪代码):

DB1.find(foo) // returns one result
    .then(getFromDB2);

function getFromDB2 (res){
    return DB2.find(res); // make a query here with mongo drivers `$in`
}
  

Mongodb : $in operator vs lot of single queries