-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?
3
  • This is basic javascript, I would highly recommend reading a basic tutorial on javascript and callbacks Commented Mar 26, 2014 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. Commented Mar 26, 2014 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) Commented Aug 24, 2016 at 11:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You are correct in your assumption as well as your general answer. The OP might find this Q&A which I answered helpful. It provides two approaches (callbacks and promises) for using mysql asynchronously.
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.
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.