I know that callback function runs asynchronously, but why?

前端 未结 3 1373
广开言路
广开言路 2020-11-22 13:39

Which part of syntax provides the information that this function should run in other thread and be non-blocking?

Let\'s consider simple asynchronous I/O in node.js

相关标签:
3条回答
  • 2020-11-22 13:45

    There is nothing in the syntax that tells you your callback is executed asynchronously. Callbacks can be asynchronous, such as:

    setTimeout(function(){
        console.log("this is async");
    }, 100);
    

    or it can be synchronous, such as:

    an_array.forEach(function(x){
        console.log("this is sync");
    });
    

    So, how can you know if a function will invoke the callback synchronously or asynchronously? The only reliable way is to read the documentation.

    You can also write a test to find out if documentation is not available:

    var t = "this is async";
    some_function(function(){
        t = "this is sync";
    });
    
    console.log(t);
    

    How asynchronous code work

    Javascript, per se, doesn't have any feature to make functions asynchronous. If you want to write an asynchronous function you have two options:

    1. Use another asynchronous function such as setTimeout or web workers to execute your logic.

    2. Write it in C.

    As for how the C coded functions (such as setTimeout) implement asynchronous execution? It all has to do with the event loop (or mostly).

    The Event Loop

    Inside the web browser there is this piece of code that is used for networking. Originally, the networking code could only download one thing: the HTML page itself. When Mosaic invented the <img> tag the networking code evolved to download multiple resources. Then Netscape implemented progressive rendering of images, they had to make the networking code asynchronous so that they can draw the page before all images are loaded and update each image progressively and individually. This is the origin of the event loop.

    In the heart of the browser there is an event loop that evolved from asynchronous networking code. So it's not surprising that it uses an I/O primitive as its core: select() (or something similar such as poll, epoll etc. depending on OS).

    The select() function in C allows you to wait for multiple I/O operations in a single thread without needing to spawn additional threads. select() looks something like:

    select (max, readlist, writelist, errlist, timeout)
    

    To have it wait for an I/O (from a socket or disk) you'd add the file descriptor to the readlist and it will return when there is data available on any of your I/O channels. Once it returns you can continue processing the data.

    The javascript interpreter saves your callback and then calls the select() function. When select() returns the interpreter figures out which callback is associated with which I/O channel and then calls it.

    Conveniently, select() also allows you to specify a timeout value. By carefully managing the timeout passed to select() you can cause callbacks to be called at some time in the future. This is how setTimeout and setInterval are implemented. The interpreter keeps a list of all timeouts and calculates what it needs to pass as timeout to select(). Then when select() returns in addition to finding out if there are any callbacks that needs to be called due to an I/O operation the interpreter also checks for any expired timeouts that needs to be called.

    So select() alone covers almost all the functionality necessary to implement asynchronous functions. But modern browsers also have web workers. In the case of web workers the browser spawns threads to execute javascript code asynchronously. To communicate back to the main thread the workers must still interact with the event loop (the select() function).

    Node.js also spawns threads when dealing with file/disk I/O. When the I/O operation completes it communicates back with the main event loop to cause the appropriate callbacks to execute.


    Hopefully this answers your question. I've always wanted to write this answer but was to busy to do so previously. If you want to know more about non-blocking I/O programming in C I suggest you take a read this: http://www.gnu.org/software/libc/manual/html_node/Waiting-for-I_002fO.html

    For more information see also:

    • Is nodejs representing Reactor or Proactor design pattern?
    • Performance of NodeJS with large amount of callbacks
    0 讨论(0)
  • 2020-11-22 13:48

    A callback is not necessarily asynchronous. Execution depends entirely on how fs.readFile decides to treat the function parameter.

    In JavaScript, you can execute a function asynchronously using for example setTimeout.

    Discussion and resources:

    How does node.js implement non-blocking I/O?

    Concurrency model and Event Loop

    Wikipedia:

    There are two types of callbacks, differing in how they control data flow at runtime: blocking callbacks (also known as synchronous callbacks or just callbacks) and deferred callbacks (also known as asynchronous callbacks).

    0 讨论(0)
  • 2020-11-22 14:00

    First of all, if something is not Async, it means it's blocking. So the javascript runner stops on that line until that function is over (that's what a readFileSync would do).

    As we all know, fs is a IO library, so that kind of things take time (tell the hardware to read some files is not something done right away), so it makes a lot of sense that anything that does not require only the CPU, it's async, because it takes time, and does not need to freeze the rest of the code for waiting another piece of hardware (while the CPU is idle).

    I hope this solves your doubts.

    0 讨论(0)
提交回复
热议问题