Async循环与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 } 

我在用户find这个用户的图像的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}); } } } 

但我的问题是,我的循环完成之前,我发现图像的回应。

所以我有一个空的数组。

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

我会使用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) });