0

I have the following code below that creates a new MongoDB document using Mongoose which does work.

async function createQuiz(questions, quizDetails) {
  const { quizName, minPoints, maxPoints } = quizDetails;
  try {
    const quiz = await Quiz.create({
      quizName,
      minPoints,
      maxPoints,
      questions,
    })
    if (quiz) console.log("success");
  } catch (e) {
    console.log(e.message);
  }
}

createQuiz(questions, quizDetails);

However, if I replace the console.log statements with return statements shown in the code below, it suddenly stops working.

async function createQuiz(questions, quizDetails) {
  const { quizName, minPoints, maxPoints } = quizDetails;
  try {
    const quiz = await Quiz.create({
      quizName,
      minPoints,
      maxPoints,
      questions,
    })
    if (quiz) return "success";
  } catch (e) {
    return e.message;
  }
}

console.log(createQuiz(questions, quizDetails));

With the return statements, the console logs "Promise { pending }." But why doesn't it log that same statement when the console.log was inside the function?

  • [This answer](https://stackoverflow.com/a/35302826/2892829) explains it. Your async function returns promise. You can use `then()` to get your returned data. – Orifjon Jul 18 '23 at 03:52
  • `async` functions, by their very definition, return a `Promise` - as [documented](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#description) – Jaromanda X Jul 18 '23 at 03:58

1 Answers1

0

As the comments said (thank you by the way), an async function always returns a promise so the proper way to write out the code so that it returns the value of the fulfilled promise is the following:

async function createQuiz(questions, quizDetails) {
  const { quizName, minPoints, maxPoints } = quizDetails;
  try {
    const quiz = await Quiz.create({
      quizName,
      minPoints,
      maxPoints,
      questions,
    })
    if (quiz) return "success";
  } catch (e) {
    return e.message;
  }
}

const createdQuiz = createQuiz(questions, quizDetails);
createdQuiz.then(data => console.log(data));