Denis Evseev Denis Evseev - 27 days ago 8
MySQL Question

How to obtain value from inner request. Function return undefined

I'm trying to get a quiz from table quizzes and after obtaining it
trying to an array of answers from table questions. But it doesn't work

I send questionDto(JSON) to this.add method, where the question I've already
added in the table and need to add answers and

var question = require('../models/question');

function Quiz() {
this.getById = function(quizId,res) {
connection.acquire(function(err, con) {
con.query('select * from quizes where `id` = ? ', quizId,
function(err, result) {
con.release();
result.questions = question.getAllByQuizId(quizId);
res.send(result);
});
});
};


question.getAllByQuizId(quizId); has to return an array of questions. Here is an implementation

function Question() {

this.getAllByQuizId = function(quizId) {
return connection.acquire(function(err, con) {
return con.query('select * from questions where `quizId` = ? ', quizId, function(err, rows) {
if (err) throw err;

con.release();

console.log(JSON.parse(JSON.stringify(rows)));
return JSON.parse(JSON.stringify(rows));
});
});
};


console.log() returns applicable value but the function return undefined

I have wasted hours to tackle. But still can't :(

Answer

You should pass a callback to handle this instead of 'return' as it has a asynchronous block in the function.

var question = require('../models/question');

function Quiz() {
  this.getById = function(quizId,res) {
    connection.acquire(function(err, con) {
      con.query('select * from quizes where `id` = ? ', quizId, 
  function(err, result) {
        con.release();
        question.getAllByQuizId(quizId, function(err, data){
           if(err) {
              throw err;
           } else {
              result.questions = data;
              res.send(result);
           }
        });
      });
    });
  };

function Question() {

  this.getAllByQuizId = function(quizId, callback) {
     connection.acquire(function(err, con) {
       con.query('select * from questions where `quizId` = ? ', quizId, function(err, rows) {
        if (err) callback(err);

        con.release();

        console.log(JSON.parse(JSON.stringify(rows)));
        callback(null, JSON.parse(JSON.stringify(rows)));
      });
    });
  };