【问题标题】:JS: async function [duplicate]JS:异步函数
【发布时间】: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!,你能告诉申请人你得到了什么吗?
  • Im not sure, but i cant 找到您在哪里缓存响应?
  • 在申请人中我得到收藏。用户信息在哪里。

标签: javascript node.js asynchronous promise async-await


【解决方案1】:

你可以试试Promise.all

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 });

    const ratingsPromise = applicant.proff.map(async item => {
        const rating = await getRating(item, applicant);
        return rating;
    });

    const ratings = await Promise.all(ratingsPromise);
    return res.json(ratings);
});

【讨论】:

    【解决方案2】:

    这部分仍然是异步的,你必须使用await

     const rating = getRating(item, applicant).then(rating => ratings.push(rating)).catch(err....
    

    【讨论】:

    • 不起作用。现在得到一个空数组。
    【解决方案3】:

    Async Functions 返回 promise,因此您需要在 getRating 之前使用 await。

    【讨论】:

    • 对这些简短的答案使用评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 2017-06-01
    相关资源
    最近更新 更多