I know that callback function runs asynchronously, but why?

前端 未结 3 1438
广开言路
广开言路 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 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.

提交回复
热议问题