Quantcast
Viewing all articles
Browse latest Browse all 11

Answer by Neeraj Bansal for What is the difference between synchronous and asynchronous programming (in node.js)

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 msecfunction 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 msecfunction someOtherTask(){  //some other task  console.log('Some Task 1');  console.log('Some Task 2');}console.log('Execution Start');//Start With this functiontimeConsumingFunction(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 immediatelysomeOtherTask();

In Short, Output is as:

Execution Start//Roughly after 105 msec (5 msec it'll take in processing)Some Task 1Some Task 2//Roughly After 510 msecError/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.


Viewing all articles
Browse latest Browse all 11

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>