Monday, 13 February 2017

javascript - How to get data from a different node.js code




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,


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...