0

I'am new in JS and had some problems with async function. I have a function, that return data from MongoDB. I create a promise, and get collection with empty object.

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

When I check in Postman, this return me array: [{},{},{}]

Please help.

Juhil Somaiya
  • 873
  • 7
  • 20
foult080
  • 3
  • 1

3 Answers3

0

this part is still async, you have to use await

 const rating = getRating(item, applicant).then(rating => ratings.push(rating)).catch(err....
Daphoque
  • 4,421
  • 1
  • 20
  • 31
0

Async Functions returns promise so you need to use await before getRating.

Shikher Garg
  • 109
  • 2
  • 7
0

You can try 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);
});

cross19xx
  • 3,170
  • 1
  • 25
  • 40