![](/img/trans.png)
[英]How do I make each worker use the first element of an list in Node.JS?
[英]How do I use async in node.js
我已經在使用mongoDB的node.js
創建了一個代碼。 一切工作正常,但是當我使用嵌套循環時,它會中斷並且不會返回正確的值。
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]
]
您的代碼非常混亂並且過於復雜。
您應該做的是(偽代碼):
DB1.find(foo) // returns one result
.then(getFromDB2);
function getFromDB2 (res){
return DB2.find(res); // make a query here with mongo drivers `$in`
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.