小编Him*_*ati的帖子

为什么javascript不等待和forEach并执行下一行

当我在 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});
Run Code Online (Sandbox Code Playgroud)

javascript node.js reactjs es6-promise angular

3
推荐指数
2
解决办法
2482
查看次数

标签 统计

angular ×1

es6-promise ×1

javascript ×1

node.js ×1

reactjs ×1