简体   繁体   English

NodeJS 是否总是/自动异步运行代码?

[英]Does NodeJS always / automatically run the code asynchronously?

I am new to this Node.js.我是这个 Node.js 的新手。 And I am afraid all of my code will run synchronously thus blocking the other requests makes my app laggy, freezing, etc when handling many request.而且我担心我的所有代码都会同步运行,因此在处理许多请求时阻止其他请求会使我的应用程序滞后、冻结等。

If I write this code:如果我写这段代码:

const array = new Array(1000000000);

for (let i=0; i < array.length; i++) {
  const item = array[i];
  // do a lot heavy lifting with each item
}

Will Node.js automatically run that code asynchronously? Node.js 会自动异步运行该代码吗?

Will it block other requests while it still run that code?它会在仍然运行该代码的同时阻止其他请求吗?

Or should I explicitly declare async/await on every piece of my code?或者我应该在我的每一段代码上明确声明 async/await 吗?

You can declare你可以声明

  • async only for a function async仅适用于 function
  • await only for a Promise (if not, Node will automatically wrap your code in a Promise)await Promise (如果没有,Node 会自动将您的代码包装在 Promise 中)

As long as you don't have any Promises, your code will be synchronous (you can think of it as Java or Python)只要你没有任何 Promise,你的代码就会是同步的(你可以认为它是 Java 或 Python)

Callbacks are not necessarily async as well, they are just functions and they run depending on the implementation of the function they are provided.回调也不一定是异步的,它们只是函数,它们的运行取决于提供的 function 的实现。

A.then(B) will run in an async fashion, where A is a Promise and B will run after the current execution ends A.then(B)将以异步方式运行,其中 A 是 Promise 而 B 将在当前执行结束后运行

That particular code will always run synchronously and will block all other script activity.该特定代码将始终同步运行,并将阻止所有其他脚本活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM