5. Event-driven asynchronous callbacks

Created Saturday 30 November 2013

// Consider:
var result = database.query ("SELECT * FROM hugetable");
console.log ("Hello World");

// This way the JS interpreter of Node.js first has to read the complete result set from the database, and then it can execute the console.log () function.
// It's similar to PHP but:
// In case of PHP execution model the web server starts its own PHP process for every HTTP request it receives. Thus a slow piece of code will result in a slow page load only for particular user.
// In the execution model of Node.js there is only one single process, so the slow piece of code will affect the whole process — everything will have to wait.

// The resolution in JS is utilizing an event loop with the concept of event-driven asynchronous callbacks.
// Example:
database.query ("SELECT * FROM hugetable", function (rows) {

var result = rows;
console.log ("Hello World");

// In this case (provided that database.query () is a part of an asynchronous library) the query is sent to database with a note that when the result of the query returns the passed anonymous function should be executed. Meanwhile console.log () will be executed, and the event loop will be entered. Node.js will cycle through this loop whenever there is nothing else to do, waiting for events.