[英]Async loop with mongodb nodejs
I have 2 collections in MongoDb : users and images我在 MongoDb 中有 2 个集合:用户和图像
users is like :用户就像:
{
"_id": ObjectID("58299fc14705d47ff852f8ae"),
"mail": "Qwerty1@test.test",
"username": "Qwerty1",
"token": "g8m7h0phrvhp774cw0xh9qkt9rhu062r2b3gigm0t1o22zkt9",
...,
"images": [
ObjectID("582c547bb7c5cc391e5a1793"),
ObjectID("582c54ecb7c5cc391e5a1794")
]
}
images is like :图像是这样的:
{
"_id": ObjectID("582c5394b522cb37d701dbe3"),
"user": "g8m7h0phrvhp774cw0xh9qkt9rhu06
"image": base64 encoded
}
I make a find in users to get ids of this user's images and I want to fill an array ( b64Images ) with aa find request to images collection.我在用户中进行查找以获取该用户图像的 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});
}
}
}
But my problem is that my loop is finished before my find in images 's response.但我的问题是我的循环在我 find in images的响应之前完成了。
So I have an empty array.所以我有一个空数组。
I know this is an asynchronous problem but I can't figure it out.我知道这是一个异步问题,但我无法弄清楚。
I would use Promise.all() approach.我会使用Promise.all()方法。
Way it works is: you collect all your promises into array, than pass that array into Promise.all
它的工作方式是:将所有承诺收集到数组中,然后将该数组传递到
Promise.all
You can start with this:你可以从这个开始:
//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.