【发布时间】:2018-08-16 18:54:02
【问题描述】:
当我在 nodejs 中创建我的 api 并尝试将 mongoose 返回计数推送到新创建的数组时,它不会等待 forEach 并执行 json.res() 并给出空响应。当我使用 setTimeout() 那么它给出了正确的结果。
let newcategories = [];
let service = 0;
const categories = await Category.find({}, '_id name');
categories.forEach(async (category) => {
service = await Service.count({category: category});
newcategories.push({ count:service });
console.log('newcategories is -- ', newcategories);
}); /* while executing this forEach it's not wait and execute res.json..*/
console.log('result --- ',result);
console.log('out newcategories is -- ', newcategories);
res.json({status: 200, data: newcategories});
【问题讨论】:
-
好吧,你不能等待forEach,但是回调函数被标记为
async(所以它会自动返回一个Promise)。所以forEach在你所有的等待准备好之前就已经完成了。只需将forEach更改为for let category of categories并在for..of块内等待 -
是的,它工作正常............非常感谢:)
-
for (let category of categories) { service = await Service.count({category: category}); newcategories.push({ _id: category._id, name: category.name, count: service }); }
-
你可以使用
reduce来连续运行这个:categories.reduce(async (previous, category) => { await previous; service = await Service.count... }, null);
标签: javascript node.js angular reactjs es6-promise