异步循环whith mongodb nodejs

时间:2016-11-16 17:08:53

标签: javascript node.js mongodb asynchronous

我在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 )找到 images 集合的查找请求。

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});
      }
   }
}

但我的问题是我的循环在找到 images 的响应之前完成。

所以我有一个空数组。

我知道这是一个异步问题,但我无法弄清楚。

1 个答案:

答案 0 :(得分:1)

我会使用Promise.all()方法。

它的工作方式是:将所有承诺收集到数组中,而不是将该数组传递到web.config

你可以从这开始:

Promise.all