0

I currently have the following code

router.get('/uri', (request,response) => {
    let final = [];
    TP.find({userID: request.userID})
    .then(tests =>{
        tests.forEach(test => {
            A.findById(test.assignmentID)
            .then(assignment => {
                final.push({
                    testID: test._id,
                    name: assignment.title,
                    successRate: `${test.passedTests}/${test.totalTests}`
                })
            })
            .catch(error => {
                console.log(error)
            })
        })
        return response.send(final);
    })
    .catch(err => {
        console.log(err);
        return response.sendStatus(500);
    })
})

The code is supposed to query 2 MongoDB databases and construct an array of objects with specific information which will be sent to the client.

However, I always get an empty array when I call that endpoint. I have tried making the functions async and make them wait for results of the nested functions but without success - still an empty array.

Any suggestions are appreciated!

0

1 Answer 1

2

forEach doesn't care about promises inside it. Either use for..of loop or change it to promise.all. The above code can be simplified as

router.get('/uri', async (request,response) => {
  const tests = await TP.find({userID: request.userID});
  const final = await Promise.all(tests.map(async test => {
    const assignment = await A.findById(test.assignmentID);
    return {
      testID: test._id,
      name: assignment.title,
      successRate: `${test.passedTests}/${test.totalTests}`
    };
  }));
  return response.send(final);
  });

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Was not aware that forEach does not care about promises. Thanks a lot for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.