0

How can i use global variable in query result function? Here is an example:

var arr = [];
var sql = "my sql code";
conn.query(sql, function(err, result){
   arr.push(result[0]);
});
console.log(arr);   // Here the result value must be displayed.

Thanks in advance.

Jake
  • 61
  • 8

1 Answers1

0

conn.query is an asynchronous method and will call the function you are passing in on completion.

Due to this, your console.log statement is executed before the global variable has been set with the result.

To solve this, place your console.log statement within the callback:

conn.query(sql, function(err, result){
   arr = result;
   console.log(arr);
});
hairmot
  • 2,975
  • 1
  • 13
  • 26
  • Thanks. What if I put a variable instead of console.log? I need to use it on the next lines (out of callback function) – Jake May 11 '18 at 12:00