I\'ve been reading nodebeginner And I came across the following two pieces of code.
The first one:
var result = database.query(\"SELECT * FROM hu
Sync Programming
Programming languages like C, C#, Java are sync programming, what so ever you write will be execute in order of your writing.
-GET DATA FROM SQL.
//Suppose fetching data take 500 msec
-PERFORM SOME OTHER FUNCTION.
//Performing some function other will take 100 msec, but execution of other
//task start only when fetching of sql data done (i.e some other function
//can execute only after first in process job finishes).
-TOTAL TIME OF EXECUTION IS ALWAYS GREATER THAN (500 + 100 + processing time)
msec
Async
NodeJs comes up with async feature, it's non-blocking in nature, suppose in any I/O task which is taking time (fetching, writing, reading), nodejs won't kept idle and wait for the task to be finish, it'll start executing next tasks in the queue, and whenever that time taking task completed it will notify using callback. Following example will help:
//Nodejs uses callback pattern to describe functions.
//Please read callback pattern to understand this example
//Suppose following function (I/O involved) took 500 msec
function timeConsumingFunction(params, callback){
//GET DATA FROM SQL
getDataFromSql(params, function(error, results){
if(error){
callback(error);
}
else{
callback(null, results);
}
})
}
//Suppose following function is non-blocking and took 100 msec
function someOtherTask(){
//some other task
console.log('Some Task 1');
console.log('Some Task 2');
}
console.log('Execution Start');
//Start With this function
timeConsumingFunction(params, function(error, results){
if(error){
console.log('Error')
}
else{
console.log('Successfull');
}
})
//As (suppose) timeConsumingFunction took 500 msec,
//As NodeJs is non-blocking, rather than remain idle for 500 msec, it will start
//execute following function immediately
someOtherTask();
In Short, Output is as:
Execution Start
//Roughly after 105 msec (5 msec it'll take in processing)
Some Task 1
Some Task 2
//Roughly After 510 msec
Error/Successful //depends on success and failure of DB function execution
Difference is clear where sync will definitely take more than 600 (500 + 100 + processing time) msec, async saves time.
The difference between these two approaches is as follows:
Synchronous way:
It waits for each operation to complete, after that only it executes the next operation.
For your query:
The console.log()
command will not be executed until & unless the query has finished executing to get all the result from Database.
Asynchronous way:
It never waits for each operation to complete, rather it executes all operations in the first GO only. The result of each operation will be handled once the result is available.
For your query:
The console.log()
command will be executed soon after the Database.Query()
method. While the Database query runs in the background and loads the result once it is finished retrieving the data.
Use cases
If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way.
In Asynchronous way you can show some Progress indicator to the user while in background you can continue with your heavy weight works. This is an ideal scenario for GUI apps.
The difference is that in the first example, the program will block in the first line. The next line (console.log
) will have to wait.
In the second example, the console.log
will be executed WHILE the query is being processed. That is, the query will be processed in the background, while your program is doing other things, and once the query data is ready, you will do whatever you want with it.
So, in a nutshell: The first example will block, while the second won't.
The output of the following two examples:
// Example 1 - Synchronous (blocks)
var result = database.query("SELECT * FROM hugetable");
console.log("Query finished");
console.log("Next line");
// Example 2 - Asynchronous (doesn't block)
database.query("SELECT * FROM hugetable", function(result) {
console.log("Query finished");
});
console.log("Next line");
Would be:
Query finished
Next line
Next line
Query finished
Note
While Node itself is single threaded, there are some task that can run in parallel. For example, File System operations occur in a different process.
That's why Node can do async operations: one thread is doing file system operations, while the main Node thread keeps executing your javascript code. In an event-driven server like Node, the file system thread notifies the main Node thread of certain events such as completion, failure, or progress, along with any data associated with that event (such as the result of a database query or an error message) and the main Node thread decides what to do with that data.
You can read more about this here: How the single threaded non blocking IO model works in Node.js
The function makes the second one asynchronous.
The first one forces the program to wait for each line to finish it's run before the next one can continue. The second one allows each line to run together (and independently) at once.
Languages and frameworks (js, node.js) that allow asynchronous or concurrency is great for things that require real time transmission (eg. chat, stock applications).
Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this case, the program is evaluated exactly in order of the statements and execution of the program is paused if one of the statements take a very long time.
Asynchronous functions usually accept a callback as a parameter and execution continue on the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).
Orginal Posted on Github: Link
Synchronous
Asynchronous
Example:
// This function is synchronous
function log(arg) {
console.log(arg)
}
log(1);
// This function is asynchronous
setTimeout(() => {
console.log(2)
}, 0);
log(3)