[英]Async loop with mongodb nodejs
我在 MongoDb 中有 2 個集合:用戶和圖像
用戶就像:
{
"_id": ObjectID("58299fc14705d47ff852f8ae"),
"mail": "Qwerty1@test.test",
"username": "Qwerty1",
"token": "g8m7h0phrvhp774cw0xh9qkt9rhu062r2b3gigm0t1o22zkt9",
...,
"images": [
ObjectID("582c547bb7c5cc391e5a1793"),
ObjectID("582c54ecb7c5cc391e5a1794")
]
}
圖像是這樣的:
{
"_id": ObjectID("582c5394b522cb37d701dbe3"),
"user": "g8m7h0phrvhp774cw0xh9qkt9rhu06
"image": base64 encoded
}
我在用戶中進行查找以獲取該用戶圖像的 ID,並且我想使用對圖像集合的查找請求來填充數組( b64Images )。
db.collection("users").find({$or : [{ username: req.params.username }, {token : req.params.username}]}).toArray(function (err, result) {
if(result.length){
var b64Images = [];
async.each(result[0].images,
function(item, callback){
db.collection("images").find({_id : item}).toArray(function (err, resulta) {
console.log(resulta[0].user);
b64Images.push(resulta[0].user);
});
callback();
},
function(err){
console.log("finished");
res.json({images : b64Images});
}
}
}
但我的問題是我的循環在我 find in images的響應之前完成了。
所以我有一個空數組。
我知道這是一個異步問題,但我無法弄清楚。
我會使用Promise.all()方法。
它的工作方式是:將所有承諾收集到數組中,然后將該數組傳遞到Promise.all
你可以從這個開始:
//this would go instead of async.each(result[0].images...
let queryPromises = [];
for (let image in result[0].images){
// toArray returns Promise if no callback passed
let queryPromise = db.collection("images").find({_id : item}).toArray();
//query execution has not started yet, so loop is working fine
queryPromises.push(queryPromise);
}
queryPromises
// queries execution starts now
.then(arrayOfResults => {
// do stuff with your results here; results arrive all at once
console.log(arrayOfResults);
}, err => {
console.log(err)
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.