What is the difference between synchronous and asynchronous programming (in node.js)

前端 未结 10 1402
情歌与酒
情歌与酒 2020-11-22 01:49

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         


        
10条回答
  •  抹茶落季
    2020-11-22 02:10

    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.

提交回复
热议问题