I am trying get value from database. Trying it out with a demo example. But I am having problem to synchronize the calls, tried using callback function. I am beginner in nod
The issue is this:
var r = db.demo(query, function(result) { data = result; });
console.log( 'Data : ' + data);
The console.log
will run before the callback function gets called, because db.demo
is asynchronous, meaning that it might take some time to finish, but all the while the next line of the code, console.log
, will be executed.
If you want to access the results, you need to wait for the callback function to be called:
var r = db.demo(query, function(result) {
console.log( 'Data : ' + result);
});
This is how most code dealing with I/O will function in Node, so it's important to learn about it.