0

I am using node js express and calling model from the controller.When I call model form controller and getting a result in result variable and print it in console.log(result) it's undefined.

Controller

var user_model=require('../models/user');

exports.get_user = function(req, res) {

    var result = user_model.get_users();

    console.log(result);
}

Model

var connection=require('../config/connection');

exports.get_users = function() {

    connection.query('SELECT * FROM users', function(err, rows) {
        if(err) {
            retrun err;
        }
        return rows;
    });
}
karan sharma
  • 605
  • 4
  • 18
Shubham Azad
  • 786
  • 2
  • 10
  • 25
  • you have to write code for async call handle. – Rahul Sharma Feb 14 '18 at 10:38
  • The problem is that the query result is being passed to a **callback** function, so the `return rows;` line will return the rows in the context of that function as opposed to the parent `get_users` function. – Mike Eason Feb 14 '18 at 10:40
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ponury-kostek Feb 14 '18 at 12:53

2 Answers2

1

Use promise to handle async calls

// **Controller** 
var user_model = require('../models/user');

exports.get_user = function (req, res) {

    user_model.get_users().then((result) => {
        console.log(result);
    }).catch(err => console.log(err));
}

// **Model** 
var connection = require('../config/connection');
exports.get_users = function () {
    return new Promise((resolve, reject) => {
            connection.query('SELECT * FROM users', function (err, rows) {
                if (err) {
                    reject(err);
                }
                resolve(rows);
            });
        }
    })
}
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37
1

This is happening because you are consoling the result before the query has finished. Node is asynchronous. Unlike php node doesn't wait for the query to finish before going to the next line.

Virendra Yadav
  • 400
  • 3
  • 9
  • then what i will do – Shubham Azad Feb 14 '18 at 11:11
  • First thing is you can use promise for the same, but if you don't want to use promise then you can create method that will wait for the result i.e. – Virendra Yadav Feb 14 '18 at 11:16
  • var connection=require('../config/connection'); exports.get_users = function() { connection.query('SELECT * FROM users',function(err,rows ){ if(err) { retrun err; } getData(rows); }); } function getData(rows) { return rows; } – Virendra Yadav Feb 14 '18 at 11:17