0

I have a problem when running TypeScript MongoDB code. In the code below I want to return the updated finalPoint and the comments variables. However, they are changed only inside the then() method. Here is my code:

  • index.ts
import { GraphQLError } from 'graphql';
import QuizModel from "../../src/models/helper/quiz";

const quizPoints = (params: {
  data: Array<{ quizID: string; answer: string }>
}) => {
  let finalPoint = 0;
  params.data.forEach((obj) => {
    QuizModel.findById(obj.quizID).then(quiz => {
      if (obj.answer === quiz?.answer) {
        finalPoint += 1;
      } 
      return finalPoint;
    }).catch(error => {
      throw new GraphQLError("No quiz found", {
        extensions: {
          code: "BAD_USER_INPUT",
          invalidArgs: obj.quizID,
          error: error
        }
      });
    });
    return finalPoint;
  });
  return finalPoint;
};

const x = quizPoints({
  data: [
    {
      "quizID": "something",
      "answer": "1"
    },
    {
      "quizID": "something2",
      "answer": "2"
    }
  ]
});

console.log(x);

The answer and the id are same as the database. The if-else statement runs well and the variable is changed inside the .then() method (e.g., return finalValue inside .then() method returns 2.

Hence, my expected result for the x is 2. However, the final result is still the initial value (e.g., x = 0). Can someone help me with this problem?

0 Answers0