-2

I have a query like below:

connection.query('SELECT * FROM `Users` WHERE `Id` = ?;', [Id], function (err, row) {
var a = row;
});

//how can I use variable `a` in here?
eddie
  • 1,252
  • 3
  • 15
  • 20
hiun
  • 33
  • 9
  • This is basic javascript, I would highly recommend reading a basic tutorial on javascript and callbacks – jeremy Mar 26 '14 at 15:01
  • You'll need to move the stuff after connection.query() into the callback or, perhaps better, call a function and pass the row variable to it. –  Mar 26 '14 at 15:31
  • You should understand that even thought in your example callback is defined inline you can pass as well function name, it's not that the results of query are inside query, they are passed to function and it can be defined elsewhere (but in accessible scope) – maurycy Aug 24 '16 at 11:44

1 Answers1

0

you really won't be able to. at least not easily.

var a;
connection.query('SELECT * FROM `Users` WHERE `Id` = ?;', [Id], function (err, row) {
    a = row;
});
//execute stuff

This will accomplish getting the value out into the next scope but where you would //execute stuff will have already happened before a is set. This is because (I'm assuming) node-mysql is asynchronous.

Joseph Dailey
  • 4,735
  • 2
  • 15
  • 18
  • You are correct in your assumption as well as your general answer. The OP might find [this Q&A](http://stackoverflow.com/questions/22109487/nodejs-mysql-dump/22110015#22110015) which I answered helpful. It provides two approaches (callbacks and promises) for using mysql asynchronously. – barry-johnson Mar 26 '14 at 19:18
  • Thank you for a assurance, I didn't delve into using callbacks as OP strictly wanted to use a after the call, but thank you for your link. – Joseph Dailey Mar 26 '14 at 21:58
  • 1
    Understand entirely. My suspicion is he most likely is somewhat new to node and might not realize he'll probably need to do what he wants inside the callback (for the reason you identified) or come up with a different approach to deferring execution until having the data he wants available. – barry-johnson Mar 26 '14 at 22:28