0

I have a code snippet in the db.js as below,

    exports.asyncGetAllData = function () {
        connection.connect(function(err) {
            connection.query(sqlGetAllData, function (err, result) {
                if (err) reject(err);
                else
                {
                    //console.log(result);
                }
                });
            });
};

And I want to get the result data when I called the function in app.js as below.

    app.get('/test/getPriceTrend', function(req, res) {
    console.log('SERVER::getPriceTrend');
    console.log(req.url);
    var data = db_connection.asyncGetAllData(); //data is undefined
    console.log(data);
    res.setHeader('Accept', 'application/json');
    res.writeHead(res.statusCode);
    //The following piece of code will send information from the database
    res.write(JSON.stringify({"hello":"world"}));
    res.end();
});

As you can see, when I tried to fetch data from db.js, it shows in the console window "the data is undefined". How can I solve this issue? Any suggestion?

Thanks in advance,

zoint
  • 108
  • 2
  • 15

2 Answers2

2

Looks like you are calling for data using async method and not waiting for the response.

var data = db_connection.asyncGetAllData(); //data is undefined
console.log(data);

Either use a function that would get you SyncData or use a callback as in:

   exports.asyncGetAllData = function (cb) {
    connection.connect(function(err) {
        connection.query(sqlGetAllData, function (err, result) {
            if (err) reject(err);
            else
            {
                //console.log(result);
                cb(data);
            }
            });
        });
};

var data = db_connection.asyncGetAllData(function(data) {
    console.log(data);
    res.write(JSON.stringify(data));
    res.end();

});
Jarek Kulikowski
  • 1,399
  • 8
  • 9
1

The easiest way to do this is to create a callback function that you pass to asyncGetAllData()

Your function would look more like this:

 exports.asyncGetAllData = function (callback) {
    connection.connect(function(err) {
        connection.query(sqlGetAllData, callback)
    })
}

Then in you app.js you pass the callback in:

db_connection.asyncGetAllData(function(err, result{
     if (err) reject(err);
     else
     {
             //console.log(result);
     }
})

You could also adjust asyncGetAllData to return a promise,which might make things a little prettier.

Mark
  • 90,562
  • 7
  • 108
  • 148