为什么在 NodeJS 中需要异步编程?

Why is async programming needed in NodeJS?

我对 NodeJS 中 async 的概念有疑问。我已经阅读了很多关于 NodeJS 中的事件轮询的内容。他们这样说:

The event loop is what allows Node.js to perform non-blocking I/O operations

Node uses the Worker Pool to handle "expensive" tasks. This includes I/O for which an operating system does not provide a non-blocking version, as well as particularly CPU-intensive tasks.

These are the Node module APIs that make use of this Worker Pool such as File System(fs)

所以,我发现 Node 使用线程池管理 I/O 运行。现在我的问题是,如果 Node 正在管理它们,为什么我们需要在 NodeJS 中使用 async programmingBlueBird?

等模块背后的原因是什么?

tl;dr: 您需要 async 来防止 Event-Loop 被阻塞。


NodeJS 使用一定数量的线程来处理客户端。基本上有两种类型的线程:

  • 事件循环(或您的主线程)
  • 工作池(或线程池)

事件循环:

基本上需要异步编程的原因:

注册所有事件后,NodeJS 进入事件循环并处理所有传入请求和传出响应。他们都通过事件循环。

工作人员池

如您所说,NodeJS 使用工作池来执行 I/O 和 CPU 密集型任务。

异步代码

为了防止阻塞主线程,你想保持你的事件循环干净,并委托某些任务。这是需要异步代码的地方。这样你的代码就变成了 non-blocking。关于 async 和 non-blocking 的术语有点模糊。澄清一下:

  • 异步代码:并行执行某些任务
  • Non-Blocking: 基本上轮询而不阻塞更多代码。

然而,在 NodeJS 中,Async 通常用于 I/O 操作。在那里它不仅仅意味着 "perform in parallel",因为它主要意味着 "don't block and get the signal"。

所以为了让NodeJS的Event Loop高效,我们不想等待一个操作完成。因此,我们改为注册一个异步 "listener"。这允许 NodeJS 有效地管理自己的资源。


BlueBird(或一般的 Promises):

BlueBird which you mentioned, aren't required anymore because NodeJS supports promises out of the box (see note here 这样的库。

Promises 只是编写异步代码的另一种方式。 Async/Await and Generator Functions 也是。

旁注:使用 async 关键字定义的函数实际上产生了一个承诺。