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;