I have a common module that will be used by several apps. The module has a object that has several methods. I import the object through the require statement but I am having problem in understanding how I can get the returned value in an asynchronous programming model. Let me clarify it here in the following over-simplified pseudo-code:
File common_module.js:
var mysql = require('mysql');
exports.f1 = function() {
var connection_pool = mysql.createPool({host: 'xxx', user:..});
connection_pool.getConnection(function(err, connection) {
connection.query('SELECT c1 from t1 where c2 = ?', value, function(err, rows) {
value_to_return = rows[0].content; //string type
});
});
return (value_to_return);
}
The main app is, lets say, main.js:
db_getval = require('./common_module.js');
console.log(db_getval.f1());
It will always complain that value_to_return is undefined because the return statement is executed without waiting for the query to complete (thanks to asynchronous programming model). Though this is a mysql query related problem here, it will be true for many other scenarios too. How do I get around this? I am missing something basic here...