0

I want to assign data return from the model, then on console.log i only see undefined

My code is:

var dmodel  = require('../models/database');
dmodel.myfunction(request,response, function (err, user) {
         console.log(user); // see data
});

Then I repair code:

var dmodel  = require('../models/database');
var userinfo;
dmodel.myfunction(request,response, function (err, user) {
            userinfo = user;
});
console.log(userinfo); // undefined, not see data

How do it ? Thanks all

This is my function:

module.exports = {
    myfunction: function (request,response, callback) {
        var query = "select * from mytable";
        //call functionexcecute query
        executeQuery(query, function (err, rows) {
            if (!err) {           
                var user = rows;            
                callback(null, user);
            } else {
                console.log(err);
            }
        });
    }
};
Garfield
  • 2,487
  • 4
  • 31
  • 54
tutran
  • 3
  • 2

2 Answers2

0

Due to asynchronous nature of javascript, code console.log(userinfo) is getting executed before the callback function is called.
Modified code:

var dmodel  = require('../models/database');
var userinfo;
dmodel.myfunction(request,response, function (err, user) {
        userinfo = user;
        console.log(userinfo);
});    

That is, your earlier code was correct. If the value printed is still undefined, that means there is some issue with the definition of function executeQuery.

user
  • 383
  • 1
  • 5
  • 20
  • Thank you, but i want to view data console.log(userinfo) outsite myfunction beacuse I want to call another funtion then i do two array data. – tutran Jan 06 '17 at 07:19
  • You have to write code is such a way that _console.log(userinfo)_ gets executed after callback function is executed. One way is to write the logic that is written after the function _dmodel.myfunction_ in another function and call that function inside the callback, once the value is assigned to _userinfo_. – user Jan 06 '17 at 07:24
  • I will try, thank you – tutran Jan 06 '17 at 08:15
0

you can use a .then promise which will wait for the first function to complete its execution

 var dmodel  = require('../models/database');
    var userinfo= {};
    dmodel.myfunction(request,response, function (err, user) {
                userinfo = user;
                return userinfo;
    }).then(function(data){
    console.log(userinfo);
    })
sac Dahal
  • 1,191
  • 2
  • 13
  • 37