-1

I am doing following code.

var data=[];
sequelize.query("SELECT `name`,`mobile` FROM `emp_table` LIMIT 0,50",function(result){
     data['main']=result;
});
console.log(data['main']); // returns 'undefined'

I have used callback hell method. But I think this is not a right way. Please help me.

Yash Thakor
  • 129
  • 3
  • 10
  • 1
    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) –  Feb 24 '18 at 11:14

3 Answers3

0

since nodeJS in asynchronous console.log(data['main']); would be executed first, as the query is been processed(fetching data from db is async call).

you can try below code to get expected output.

var data=[];
sequelize.query("SELECT `name`,`mobile` FROM `emp_table` LIMIT 
0,50",function(result){
data['main']=result;
console.log(data['main']);
});
Yash Thakor
  • 129
  • 3
  • 10
0

I'm not sure what you mean with the callback hell method. But you're using a callback (the function supplied as a parameter) in the query() call. That function is only being called whenever query()'s body calls it. Making it behave asynchronous.

Problem now is, is the console.log is outside this 'async-loop' and ran sequentially. So data['main'] is actually undefined by the time console.log is called.

To fix it do this:

var data=[];
sequelize.query("SELECT `name`,`mobile` FROM `emp_table` LIMIT 0,50",function(result){
     data['main']=result;
     console.log(data['main']);
});

Move console.log into the callback.

Alex
  • 838
  • 1
  • 14
  • 16
0

You need to use promise when fetching data from db. You can print your data in then part of your code. Example: Service that calls fetch data from db and returns a promise.

exports.getAllUsers = function() {
    // this is the place where you will execute your query.
    return models.user.findAll();
};

In the controller, the data is printed as.

userService.getAllUsers().then(function (result) {
        if (result != null) {
            res.status(200).json({
                status: "success",
                data: result
            });
        } else {
            res.status(404).json({
                status: "fail",
                data: "No data found"
            });
        }
    }
Shahzeb Khan
  • 3,582
  • 8
  • 45
  • 79