I am trying to write a module which returns a value from MySQL database based on the key that gets passed to the function.
The below code when tested in standalone works fine, i was able to get the result back, but when i try to get the results from a function call i get undefined.
var value = getKey("tc_api_user_key");
I suspect it due to the return statements. How should i make the calling function wait for the results.
var mysql = require('promise-mysql')
, dbConnect = require('../connection.js')
, fs = require('fs')
, select = fs.readFileSync(__dirname + '/queries/getallkey.sql').toString();
let getKey = (key_id) => {
mysql.createConnection(dbConnect.getConnection()).then(function(conn){
var result = conn.query(select);
conn.end();
return result;
}).then(function(rows){
// Logs out a list of hobbits
Object.keys(rows).forEach(function(key) {
var item = rows[key];
if (key_id == item.key_id) {
return item.key_value;
}
});
});
}
var value = getKey("tc_api_user_key");
console.log(value)
This issue is not with the conn.query(), the function works as expected if console.out the result is used, its just not usable in function call. May be due to the async nature of the call.