【发布时间】:2020-02-19 11:31:01
【问题描述】:
我是 JS 新手,在使用异步函数时遇到了一些问题。 我有一个函数,它从 MongoDB 返回数据。我创建了一个承诺,并使用空对象获取集合。
async function getRating(item, applicant) {
let arr = await Applicant.find({ proff: item }).sort({ ball: "desc" });
let rating = arr.findIndex(item => item._id.equals(applicant._id));
let spec = await Spec.findById(item);
const el = { spec, rating };
return el;}
router.get("/test", auth, async (req, res) => {
let applicant = await Applicant.findOne({ user: req.user.id });
let ratings = [];
applicant.proff.forEach(item => {
const rating = getRating(item, applicant)
.then(rating => ratings.push(rating))
.catch(err => console.log(err));
ratings.push(rating);
});
await res.json(ratings);
});
当我签入 Postman 时,这会返回给我数组:[{},{},{}]
请帮忙。
【问题讨论】:
-
欢迎来到 SO!,你能告诉申请人你得到了什么吗?
-
I
m not sure, but i cant 找到您在哪里缓存响应? -
在申请人中我得到收藏。用户信息在哪里。
标签: javascript node.js asynchronous promise async-await