> On Mar 24, 2015, at 12:21 PM, [email protected] wrote:
>
> Hello
> I am a beginner and struggling with the asynchronous nature of Node.js,
> could you please give me a hint how to deal with following issue.
>
> In my test code below, I do an SQL query. I will get callbacks for each
> result and I will then add counter value and store the result into an array.
> This all works fine because I am inside "this query process namespace" or
> whatever.
>
> After the query is over, I will print out the array and the counter. They are
> both undefined! This I assume comes from the fact that inside my callbacks
> the process and environment was different. I have few questions: first one
> is, am I right with my assumptions that its not possible to get "stored" the
> parameter values somehow inside the callbacks to be used later outside the
> callbacks?
>
> Should I try to handle and finish the whole operation inside the query
> callback, so that I dont even have to try to store these values outside this
> scope?? Any help and hints are very welcome :-)
>
Exactly i.e., handle and finish the whole operation inside the query callback.
You are setting up a bunch of event handlers, and then immediately accessing
the values. The values are not going to exist until the event occurs and the
data is copied over into your variables.
In general, you are going to encounter this over and over: any code you add
preceding an async call (such as your DB query) should not depend on the result
of the async call. You can avoid this trap in a generic way by adopting a more
functional style of programming (not my cup of tea) or by using something that
makes the flow more sequential/imperative (my cup of tea: Promises).
—ravi
> function readDB() {
> var counter = 0;
> var testArray = new array();
> var connection = mysql.createConnection({
> host : 'localhost',
> user : 'root',
> password : '',
> database : 'TestDB'
> });
> connection.connect();
> var query = connection.query('SELECT * from Users');
>
> query.on('error', function(err) {
> throw err;
> });
> query.on('fields', function(fields) {
> });
> query.on('result', function(row) {
> counter += 1;
> testArray[counter] = row;
> console.log("testArray: " + testArray);
> });
>
> connection.end();
> console.log("testArray: " + testArray + ", counter: " +
> counter);
> }
--
Job board: http://jobs.nodejs.org/
New group rules:
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/nodejs/2D9604A1-1BD8-4878-8762-249B9F2622A4%40g8o.net.
For more options, visit https://groups.google.com/d/optout.