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;
    });
}
3
  • you have to write code for async call handle. Commented Feb 14, 2018 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. Commented Feb 14, 2018 at 10:40
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Feb 14, 2018 at 12:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

then what i will do
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.
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; }
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);
            });
        }
    })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.