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

前端 未结 10 1620
情歌与酒
情歌与酒 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:16

    Asynchronous programming in JS:

    Synchronous

    • Stops execution of further code until this is done.
    • Because it this stoppage of further execution, synchronous code is called 'blocking'. Blocking in the sense that no other code will be executed.

    Asynchronous

    • Execution of this is deferred to the event loop, this is a construct in a JS virtual machine which executes asynchronous functions (after the stack of synchronous functions is empty).
    • Asynchronous code is called non blocking because it doesn't block further code from running.

    Example:

    // This function is synchronous
    function log(arg) {
        console.log(arg)
    }
    
    log(1);
    
    // This function is asynchronous
    setTimeout(() => {
        console.log(2)
    }, 0);
    
    log(3)

    • The example logs 1, 3, 2.
    • 2 is logged last because it is inside a asynchronous function which is executed after the stack is empty.

提交回复
热议问题