0

I have array and i want to store the query result in array below is the code

var button_settings=[];
con.query("SELECT * from ht_button", function (err, result, fields){
   if (err) throw err;
   button_settings.push(result);
});
console.log(button_settings);

it shows [] i want the stored result.

5 Answers5

1

You are querying the database which is asynchronous in nature thus the console.log does not wait for the result from con.query and executes immediately after that. Thus, you get [] printed. But if you have records in result after the query is completed then you will get the array printed in console if you put the console.log(button_settings); inside the con.query function like this:

Change code to

var button_settings=[];
con.query("SELECT * from ht_button", function (err, result, fields){
   if (err) throw err;
   button_settings.push(result);
   console.log(button_settings);  //console after the query completes
});

So, to make the flow work like a synchronous where you will use the value of button_settings, create a private function like this,

var button_settings=[];
con.query("SELECT * from ht_button", function (err, result, fields){
   if (err) throw err;
   button_settings.push(result);
   _processButtonSettings();
});

//put all your code related to button_settings here
function _processButtonSettings(){
  console.log(button_settings);
  //and more code...
}
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • i want the result out side of the query block, i am using mysql –  Apr 21 '18 at 08:32
  • This is asynchronous call so what you can do is put all your code in a private function and call that from inside `con.query` callback so that it will get the value of `button_settings` at that time. @VikasChauhan. – Ankit Agarwal Apr 21 '18 at 08:34
  • i want value out side of function not in another function. i have tried the same thing in PHP its working fine but i don't know why its not working in node js –  Apr 21 '18 at 08:49
  • Then @VikasChauhan check this https://stackoverflow.com/questions/32850045/node-js-synchronous-queries-with-mysql#answer-32850828 – Ankit Agarwal Apr 21 '18 at 08:53
0

connection.query is async, which mean when your call your console.log(button_settings), button_settings has not been set yet.

var button_settings=[];
con.query("SELECT * from ht_button", function (err, result, fields){
   if (err) throw err;
   else setValue(result);
});
function setValue(value) {
  button_settings = value;
  console.log(button_settings);
}
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27
0

Try to implement Promise here

console.log

fired before the query function callback

underscore
  • 6,495
  • 6
  • 39
  • 78
0

The correct way to solve this issue is to write console.log inside the callback. That's what is highly recommended.

Now coming to the part what you want i.e. writing console.log after con.query in the same block and also you don't want console.log in seperate function (this is what I understand from the question and your comments in other answers)

To achieve this you'll have to wrap con.query in a promise and use await to wait till the promise resolves.

var button_settings=[];
await new Promise(function(resolve, reject){
    con.query("SELECT * from ht_button", function (err, result, fields){
        if (err) reject(err)
        button_settings.push(result);
        resolve()
    });
}).catch(function(err){/* handle err */})
console.log(button_settings);

How the only problem is that you can only use await inside an async function. So let's wrap the whole in code an async function

Final code:

async function doStuff(){
    var button_settings=[];
    await new Promise(function(resolve, reject){
        con.query("SELECT * from ht_button", function (err, result, fields){
            if (err) reject(err)
            button_settings.push(result);
            resolve()
        });
    }).catch(function(err){/* handle err */})
    console.log(button_settings);
}
doStuff();

I have not tested this code with actual mysql thing... But I here's a equivalent test :

async function doStuff(){
  var button_settings=[];
  await new Promise(function(resolve, reject){
    setTimeout(function(){
      button_settings = ["foobar"];
      resolve();
    },1000)
  });
  console.log(button_settings);
}
doStuff();
Devansh J
  • 4,006
  • 11
  • 23
  • I have tried your solution but its not working let me check it again and get back to you. thanks for solution. –  Apr 21 '18 at 14:18
  • i have tried this code. var array_name = []; con.connect(function(err) { async function doStuff(){ var button_settings=[]; await new Promise(function(resolve, reject){ con.query("SELECT * FROM vm_admin", function (err, result, fields) { if (err) reject(err) button_settings.push(result); resolve(); }); }).catch(function(err){/* handle err */}) console.log(button_settings); } doStuff(); }); but its giving error : Unexpected token function –  Apr 21 '18 at 14:20
  • @VikasChauhan can you tell which function token is the error refering by seeing the line and column number... Also please share which nodejs version you are using... – Devansh J Apr 21 '18 at 14:26
  • async function doStuff(){ ^^^^^^^^ SyntaxError: Unexpected token function at Object.exports.runInThisContext (vm.js:76:16) at Module._compile (module.js:542:28) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:394:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:509:3 –  Apr 21 '18 at 14:40
  • async functions are not supported your nodejs version check this [table](https://node.green/#ES2017-features-async-functions) You'll have to update your nodejs verison – Devansh J Apr 21 '18 at 14:45
  • downloaded , node version v9.11.1 still same issue –  Apr 21 '18 at 15:22
  • @Vikas Chauhan what's the error now? same? Just recheck your version by "node --version" in your shell. Because I doubt it's updated – Devansh J Apr 21 '18 at 15:23
  • its updated i have checked and i found the issue i am updating answer , thanks all of you for support. have a awesome day ahead ;) –  Apr 21 '18 at 15:51
  • @Vikas Chauhan Np, happy to help :) – Devansh J Apr 21 '18 at 16:00
  • @Vikas Chauhan dude you can't copy my code to write your own answer and then accept it... That's not how StackOverflow works... Imagine if I didn't post this answer would have you been able to write your own answer or solve your problem? My answer deserves to be accepted... I would love to hear your reply – Devansh J Apr 23 '18 at 19:09
  • you are right , its done by mistake so sorry for that –  Apr 24 '18 at 08:59
0
   var res1=[];
   var res2=[];
   var res3=[];
   async function doStuff(){

    await new Promise(function(resolve, reject){
        con.query("SELECT * FROM vm_admin", function (err, result, fields) {
            if (err) throw err;
            resolve();
            res1.push(result);
        });
    });     

    await new Promise(function(resolve, reject){
        con.query("SELECT * FROM vm_banks", function (err, result, fields) {
            if (err) throw err;
            resolve();
            res2.push(result);
        });
    });     

    console.log(res1);  
    console.log('----------------');
    console.log(res2);  

}
doStuff();

I have checked above code and its working fine , thanks all of you for your quick support.