【问题标题】:Async loop with mongodb nodejs使用 mongodb nodejs 的异步循环
【发布时间】:2021-05-28 08:09:45
【问题描述】:

我在 MongoDb 中有 2 个集合:usersimages

用户就像:

{
"_id": ObjectID("58299fc14705d47ff852f8ae"),
"mail": "Qwerty1@test.test",
"username": "Qwerty1",
"token": "g8m7h0phrvhp774cw0xh9qkt9rhu062r2b3gigm0t1o22zkt9",
 ...,
"images": [
    ObjectID("582c547bb7c5cc391e5a1793"),
    ObjectID("582c54ecb7c5cc391e5a1794")
]
}

图片就像:

{
"_id": ObjectID("582c5394b522cb37d701dbe3"),
"user": "g8m7h0phrvhp774cw0xh9qkt9rhu06
"image": base64 encoded
}

我在 users 中进行查找以获取该用户图像的 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 的响应中找到之前完成。

所以我有一个空数组。

我知道这是一个异步问题,但我想不通。

【问题讨论】:

标签: javascript node.js mongodb asynchronous


【解决方案1】:

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

它的工作方式是:你将所有的 Promise 收集到数组中,然后将该数组传递给 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)
   });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    相关资源
    最近更新 更多