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
  • What's the issue here? Commented Apr 21, 2018 at 8:27
  • i am not able to get the stored values Commented Apr 21, 2018 at 8:28
  • You need a promise here. console.log fired before the function callback Commented Apr 21, 2018 at 8:29
  • can you give any code sample please , thanks Commented Apr 21, 2018 at 8:31
  • stackoverflow.com/questions/9022099/… Commented Apr 21, 2018 at 8:33

5 Answers 5

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...
}
Sign up to request clarification or add additional context in comments.

4 Comments

i want the result out side of the query block, i am using mysql
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.
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
Then @VikasChauhan check this stackoverflow.com/questions/32850045/…
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();

11 Comments

I have tried your solution but its not working let me check it again and get back to you. thanks for solution.
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
@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...
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
async functions are not supported your nodejs version check this table You'll have to update your nodejs verison
|
0

Try to implement Promise here

console.log

fired before the query function callback

1 Comment

Having such a reputation does not suites you for giving such an abstract answer
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);
}

3 Comments

This will surely do not work, as I said the query to db is asynchronous so your code still fails.
Check now @VikasChauhan
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
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.