0

Why the second console.log still prints 0? How can I override the user_id from connection query function?

var user_id = 0; //initializing

connection.query('Select id from users', function (err, result) {

    if (err) throw err;
    user_id = result[0].id;

    console.log(user_id); //Prints 101
});

console.log(user_id); //Prints 0

}
Nazmul Islam
  • 61
  • 3
  • 7

1 Answers1

-1

By Declaring you variable globally you can update that variable inside any function or that functions callback.

And in global scope it is easy if you define that variable at top of your Code.

  • How does this answer the question? He already have a variable outside of the query callback scope. – Marcos Casagrande May 12 '18 at 22:16
  • If you take a look at the code he posted there is one brace at the end which indicates that variable declaration is not in global scope. – Muhammad Zubair Saleem May 12 '18 at 22:18
  • How a global scope variable solves this, he's printing that variable before the asynchronous query finishes, this is an async problem, not solved by a variable in the global scope. – Marcos Casagrande May 12 '18 at 22:19
  • Yes, This can be an async problem but in more than 95% cases this global thing actually works in async mode too. – Muhammad Zubair Saleem May 12 '18 at 22:29
  • A global scope variable is bad practice, and you didn't provide an actual answer, you should edit your answer or just vote to close as duplicate. – Marcos Casagrande May 12 '18 at 22:37
  • Just Out of curiosity how we can imply that global scope variables are a bad practice when the application process requires that? In some specific cases where you need that I/O Blocking thing in case of synchronous execution you can imply that and in my experience, if you have to do stuff in the synchronous pattern you must go for another approach rather saying this bad practice. – Muhammad Zubair Saleem May 12 '18 at 23:02
  • The OP isn't using a synchronous pattern. he's doing an async operation. Your answer isn't helpful at all, you're not adding anything. The OP is using a variable outside of the callback scope, which in this case is the same as a global variable, which is your answer, so if you want your answer to be good, expand it. Otherwise telling to use a global variable without any example or further explanation is bad practice. – Marcos Casagrande May 12 '18 at 23:40
  • 1
    This Makes sense in above all :) Thanks will update. – Muhammad Zubair Saleem May 12 '18 at 23:42