Reputation: 13
I have this function to connect to my DB and consult something in it.
function conn (text){
var mysql = require("mysql");
var connection = mysql.createConnection({
connectionLimit : 100, //important
host : 'xxx.xxx.xxx.xxx',
user : 'xxxxxx',
password : 'xxxxxxx',
database : 'xxxxxxxx'
});
connection.connect();
var queryString = 'SELECT usuario.idUsuario FROM usuario WHERE usuario.nickname = ' + '"' + text + '"';
function getID(text, callback){
connection.query(queryString, function(err, rows, fields) {
var id;
if (err){
callback(err, null);
}else{
for (var i in rows) {
id = rows[i].idUsuario;
}
callback(null, id);
}
});
}
var result;
getID(text, function(err, content) {
if (err) {
console.log(err);
} else {
result = content;
}
});
connection.end();
};
Now, i need to get the result in other variable to use it in other functions inside my JS file. How can i get that value without get code inside the variable?
Upvotes: 0
Views: 2641
Reputation: 2191
Your function conn (text)
is fetching data using callbacks, you need to carry that pattern all the way to the consuming code. I'm not sure what the "other functions" look like, but let's pretend one looks like this:
function awesomeFunction() {
var sweetResult = conn('sweet nickname');
alert(sweetResult);
}
conn
is going to connect and issue a query to your db. You do not want to stop everything else and wait for the result to come back, you want the db library to call you when it has results, hence the callbacks. Since the database isn't stopping everything, control returns to your conn
function, and then back to awesomeFunction
, and passes to the next line alert(sweetResult)
. But wait! You didn't return anything from conn, but more important, the database hasn't even called back with results yet!
So, you need awesomeFunction
to look more like this:
function awesomeFunction() {
conn('sweet nickname', function(err, sweetResult) {
alert(sweetResult);
});
}
Which means, conn
needs to accept and use a callback too:
function conn (text, resultsAreInCB){
...
connection.query(queryString, function(err, rows, fields) {
var id;
connection.end();
if (err){
resultsAreInCB(err, null);
} else {
for (var i in rows) {
id = rows[i].idUsuario;
}
callback(null, id);
}
});
...
};
Upvotes: 1