-1

The questionController below is suppose to handle a /question path and return a response. I am just testing the connection to the database at present, thus returning a hard coded value.

However, the value received at client is not value of q but the following:

[
  {
    "message": "[object Promise]"
  }
]

What am I doing wrong?

question.js

const mongoUtils = require('../mongoUtils');
var db ;

var Question = require('../schema/question')

async function getQuestion(){
  var q = null;
  try {
    //const db = dbClient.db("Questions");
    console.log(`db in getQuestion ${db}`);
    const areaCollection = await db.collection("Area");
    console.log(`area collection is ${areaCollection}`);
    q = Question({
      description: "some description",
      hints: ["hint1", "hint2"],
      topic: 'area'
    });
  } catch(exception) {
    console.log(`something bad happened in dbconnect: ${exception}`);
  } finally {
    console.log(`question object : ${JSON.stringify(q)}`);
    
  }
  return q
  
}

exports.questionController = function (req, res) {
  db = mongoUtils.getDb();
  console.log(`db in question is ${db}`);
  console.log(`connected to database ${db.databaseName}`);
    
  var question = getQuestion();
  console.log('question page');
  //var response = res.json([{"message": `${question}`}]);
  var response = [{"message": `${question}`}];
  console.log(`returning response: ${JSON.stringify(response)}`)
  return res.json(response);
}
Manu Chadha
  • 15,555
  • 19
  • 91
  • 184
  • Does this answer your question? [Async function returning promise, instead of value](https://stackoverflow.com/questions/51338277/async-function-returning-promise-instead-of-value) – jonrsharpe Jul 30 '23 at 14:06

2 Answers2

0

Happy to accept alternate answer. Seems the correct way is to use then

getQuestion().then((question)=>{
    console.log('question page');
    //var response = res.json([{"message": `${question}`}]);
    var response = [{"message": `${question}`}];
    console.log(`returning response: ${JSON.stringify(response)}`)
    return res.json(response);
  } );
Manu Chadha
  • 15,555
  • 19
  • 91
  • 184
0

The getQuestion function returns a promise which you need to resolve to get the result.

exports.questionController = async function (req, res) {
  const question = await getQuestion();
  const response = [{ message: question }];
  return res.json(response);
}
Pádraig Galvin
  • 1,065
  • 8
  • 20