我试图从 MongoDB 获取一些数据,在发送它们之前我必须编写一些代码,但在循环结束时,我的回调没有被调用!
var itemsProcessed = 0;
async.forEach(categories, function(category, cb) {
Audit.find({
'category_id': category._id
}, 'created_at updated_at user_Id entreprise_id nom _id category_id', function(err, auds) {
category.products = [];
category.count = 0;
if (err) res.send(err);
category.products = auds;
category.count = auds.length;
itemsProcessed++;
if (itemsProcessed == categories.length) {
cb();
}
});
}, function() {
res.json(categories);
});
如何在执行完所有循环后发送所有类别?感谢您的帮助。
最佳答案
最好结合使用 map、await async 和 Promise.all。
它的工作原理是
let a=array.map(dbFunction);
a=await Promise.all(a);
res.send({a});
你的情况,你的代码看起来像
try {
let resp = categories.map(async (category) => {
const auds = await Audit.find(
{ 'category_id': category._id },
'created_at updated_at user_Id entreprise_id nom _id category_id'
);
category.products = auds;
category.count = auds.length;
return category;
});
resp = Promise.all(resp);
res.send({ resp });
} catch (error) {
res.send({ error });
}
关于javascript - 异步:循环后回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51416840/