I understand that Node.js has the concept of event-driven, asynchronous callbacks, by utilizing an event loop.
database.query("SELECT * FROM hugetable", function(rows) { var result = rows; });
console.log("Hello World");
Here, instead of expecting database.query() to directly return a result to us, we pass it a second parameter, an anonymous function. Now, Node.js can handle the database request asynchronously. Provided that database.query() is part of an asynchronous library, this is what Node.js does: just as before, it takes the query and sends it to the database. But instead of waiting for it to be finished, it makes a mental note that says "When at some point in the future the database server is done and sends the result of the query, then I have to execute the anonymous function that was passed to database.query()."
I am trying the same with a sample code (as I am a newbie and not reached till Node.js DB interactions):
[root@example]# cat server8.js
function myfun(noparm , afterend)
{
for ( var i =0; i < 10; i ++)
console.log("The valus is " + i);
}
function mynextfn()
{
console.log("Hello World");
}
function afterend()
{
console.log("Hello afterend");
}
myfun(0, afterend);
mynextfn();
[root@idc-bldtool01 example]# node server8.js
The valus is 0
The valus is 1
The valus is 2
The valus is 3
The valus is 4
The valus is 5
The valus is 6
The valus is 7
The valus is 8
The valus is 9
Hello World
[root@iexample]#
As such I do not see the " concept of event-driven, asynchronous callbacks, by utilizing an event loop" ?
Can anyone please help me in implementing some basic examples?
You hand the afterend
function over as a parameter, but you never call it.
Your function myfun
must be:
function myfun(noparm , afterend)
{
for (var i = 0; i < 10; i++) {
console.log("The valus is " + i);
}
afterend();
}
Then that what you expect to will happen ;-)
And: Second thing is that your myfun
function is completely synchronous. So there is no chance for Node.js to run mynextfn
before the content of the myfun
function.
Potentially afterend
will be run before myfun
, that depends on timing issues as both do not do any heavy lifting.