[英]How do I use async in node.js
I have created a code in node.js
, which use mongoDB. 我已经在使用mongoDB的node.js
创建了一个代码。 Everything is working fine, but when I use nested loop, it break and don't return the proper values. 一切工作正常,但是当我使用嵌套循环时,它会中断并且不会返回正确的值。
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 #########');
});
In my console message its showing 在我的控制台消息中显示
console.log('######### LAST #########');
All Values
console.log('######### LAST #########');
After that 之后
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
All Values;
console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
I want to use async in my code, so that all data fetching occur as below: 我想在我的代码中使用async,以便所有数据提取如下:
mainarray =
[
[array1] = All Values
[array2] = [0]
[1]
]
mainarray =
[
[array1] = All Values
[array2] = [0]
[1]
]
Your code is very confusing and overly complicated. 您的代码非常混乱并且过于复杂。
What you should do is (psuedo code): 您应该做的是(伪代码):
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 Mongodb:$ in运算符与很多单个查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.