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,

1
  • Take a look here. Commented Jul 16, 2017 at 1:09

2 Answers 2

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();

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

Comments

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.

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.