Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js - Retrieving data from a database (mysql) - delay

Node.js - Retrieving data from a database (mysql) - delay


I am loading data from the database using mysql drivers for node.js.

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 = [];

  '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");




ID: 1
Problem courtesy of: Jenan


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:

Others have also recommended this video introducing Node from Ryan Dahl:

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

Solution courtesy of: Rohan Singh


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js - Retrieving data from a database (mysql) - delay


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription