skip to Main Content

I have an asynchronous route at /api/dashboard the code is below:

router.get("/", async (req, res, next) => {
  let userID
  try {
    const jwt = req.headers.authorisation.split(" ")[1];
    const { payload } = verifyToken(jwt, res);
    userID = payload?.id;
  } catch (err) {
    next(err)
  }

  let numberCompletedExams
  try {
    numberCompletedExams = await ExamResult.find()
    .then(examResults =>
      // find the total number of completed exams belonging to a particular student
      examResults.reduce((acc, examResult) => {
        if (!matchesUser(examResult.userId, userID)) {
          return acc
        }
        return acc + 1
      },0)
    )
  } catch (err) {
    next(err)
  }

  let numberActiveExams
  try {
    numberActiveExams = await Exam.find()
      .then(exams =>
        // find the total number of active exams belonging to a particular student
        exams.reduce((acc, exam) => {
          if (!notDue(exam.due)) return acc
          return acc + 1
        },0)
      )
  } catch (err) {
    next(err)
  }

  return {
    total: numberCompletedExams + numberActiveExams,
    active: numberActiveExams,
    completed: numberCompletedExams
  }
});

I know that the variables numberCompletedExams and numberActiveExams get resolved to their correct values since they log to the console but the function never returns ie. infintely loads when using postman at the route "api/dashboard". How do I get the function to return?

2

Answers


  1. Chosen as BEST ANSWER

    Changing to this code works

    return res.status(200).json({
        total: numberCompletedExams + numberActiveExams,
        active: numberActiveExams,
        completed: numberCompletedExams
      })
    

  2. Its missing res.json(), As its a controller attached to route, To return that http response you must use:

    return res.json({ 
        total: numberCompletedExams + numberActiveExams,
        active: numberActiveExams,
        completed: numberCompletedExams
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search