2017-10-05 34 views
0

我的下面的代码是射击异步下一个回调之前,我的照片find()承诺完成。 我以为async.forEach直到next被调用才会启动。异步forEach下一个方法不等待

我试图让我的照片[0]以与类别相同的顺序出来:item.strId被传入。现在它不以那种方式工作并返回随机顺序。有没有办法在forEach的下一个循环发生之前等待承诺。我认为这就是异步的回调。或者我误解了它。

exports.fetchHomeCollection = (req, res, next)=>{ 
    const collection = []; 

    Category.find({count : { $gt : 0}}).then(categories =>{ 
    async.forEach(categories, function(item, next){ 
     console.log("item.strId = ", item.strId); 
     Photo.find({isDefault:true, category:item.strId}).then((photo)=>{ 
      console.log("photo = ", photo); 
      collection.push(photo[0]); 
      next(); 
     }); 
    }, 
    function(err){ 
     if(err) console.log("fetchHomeCollection async forEach error"); 
     res.send(collection); 
    }); 
    }) 

} 

我用global.Promise作为我mongoose.promise

const mongoose = require('mongoose'); 
mongoose.Promise = global.Promise; 

回答

0

不要async.js混合承诺。他们在一起工作不好。

exports.fetchHomeCollection = (req, res, next)=>{ 
    async.waterfall([ 
     function (cb) { 
      Category.find({ count: { $gt : 0 }}, cb); 
     }, 
     function (categories, cb) { 
      async.map(categories, function (category, next) { 
       Photo.findOne({ isDefault:true, category: category.strId }, next); 
      }, cb); 
     } 
    ], 
    function (err, photos) { 
     if (err) 
      console.log("fetchHomeCollection async forEach error"); 
     res.send(photos); 
    }); 
};