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
This is how Node works — using an asynchronous model. First all your code as written executes, including
console.log(users). At this point,usersis an empty array.Only once all your imperative instructions have executed do callbacks get fired — such as your
selectCbfunction. It’s only once this callback runs that you can have access tousers.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")andconsole.log(users)lines into the body of theselectCbfunction.