0

I am loading data from the database using mysql drivers for node.js. https://github.com/felixge/node-mysql

I want to load data into the array. When I am loading data into the array - there is a delay and the array is empty.

I want to retrieve data and then write the lines - console.log("END QUERY"); console.log(users);

var users = [];

client.query(
  'SELECT * FROM users',
  function selectCb(err, results, fields) {
    if (err) {
      throw err;
    }

if (results.length > 0) {
          var reader = results[0];
          console.log("ID: " + reader['id']); //ADD string - 'ID: 1'
          users = [reader['id']]
      } 
     }
);

console.log("END QUERY");

console.log(users);

OUTPUT:

WRITE LINE:

END QUERY
[]
ID: 1

1 Answer 1

2

This is how Node works — using an asynchronous model. First all your code as written executes, including console.log(users). At this point, users is an empty array.

Only once all your imperative instructions have executed do callbacks get fired — such as your selectCb function. It's only once this callback runs that you can have access to users.

This is the entire point and purpose of Node, actually, and it is very important to understand the fundamentals here. You can read more about it at: http://shinetech.com/thoughts/articles/139-asynchronous-code-design-with-nodejs-

Others have also recommended this video introducing Node from Ryan Dahl: http://www.youtube.com/watch?v=jo_B4LTHi3I

In your specific case, I would move the console.log("END QUERY") and console.log(users) lines into the body of the selectCb function.

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

Comments

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.