Asynchronous Vs synchronous in NodeJS

后端 未结 4 541
自闭症患者
自闭症患者 2021-02-08 01:59

I\'m new to NodeJS. I have seen there are separate asynchronous and synchronous functions for the same task (ex: {fs.writeFile,fs.writeFileSync} , {fs.read, f

4条回答
  •  你的背包
    2021-02-08 02:33

    The reason for having both sync and async verisons of those operations is that they can be time-consuming, and since node.js has a single-threaded main event loop, you do not under any circumstances want to block the event loop with slow synchronous function calls.

    That is why everything is done using callbacks (or promises, vows, or what your particular taste in async stuff happens to be) instead. This way, you can have an event loop that just calls an async function and handle the result of the async function in a callback, when it happens to be done.

    This is one of the major strengths of node.js, and one of the basic rules: "do not block the main event loop".

提交回复
热议问题