在JavaScript并行中是异步吗?

发布于 2025-01-24 12:49:04 字数 134 浏览 2 评论 0原文

JavaScript代码在单个线程上运行,在事件循环中,当方法按下Web API返回回调函数到队列,侦听器队列和CallStack是空的按下PUSH CALLBACK函数在CallStack中执行它,因此异步执行实际上只是更改更改的执行顺序功能?为什么?

JavaScript code runs on a single thread, in event loop when method push to web apis return callback function to queue, listener queue and callstack is empty push callback function execute it in callstack, so the asynchronous execution is really just changing the execution order of the functions? Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

-小熊_ 2025-01-31 12:49:04

由于JavaScript是单线程,因此从技术上讲,它仅是并发,而不是并行。也就是说,没有两个说明是同时执行的,但是事件循环允许我们协调执行指令的顺序,以使某些说明是 nonthbocking

要查看为什么这很有用,请考虑以下步骤序列:

  1. 对API进行呼叫
  2. 其他工作,

步骤1可能需要一段时间,我们可能想在此期间等待其他工作时进行其他工作。完成,使其成为阻止调用。在纯粹的顺序世界中,这意味着步骤2直到步骤1完成后才执行。相比之下,如果我们制作此异步,因此非阻滞,我们可以执行步骤1和2 同时。发生这种情况是因为事件循环将首先运行我们的同步代码的迭代(步骤2),然后运行我们的异步代码(步骤1) - 它正在更改订单指令以某种方式执行我们的代码是非阻滞。有趣的是,这意味着在下一个代码的同步迭代之后,异步延迟为0秒将运行

假设我们介绍了步骤3,其中我们需要步骤1中的API调用的响应。为此,我们可以使用 async-await ,它将是 blocking 直到步骤1完成。这不是纯粹的顺序,因为步骤2不需要等待步骤1完成,但是在步骤3中,我们能够通过 async-await 在代码中创建一个同步点。因此,我们能够将代码非阻滞在重要的情况下保持不变,并且仍然引入特定的事件序列。

Due to JavaScript being single-threaded, it is technically only concurrent, not parallel. That is, no two instructions are ever executed at the same time, but the event loop allows us to coordinate the order in which instructions are executed such that certain instructions are non-blocking.

To see why this is useful, consider the following sequence of steps:

  1. Make a call to an API
  2. Do some other work

Step 1 could take quite some time, and we may want to do some other work in the meantime while we wait for it to complete, making it a blocking call. In a purely sequential world, this means that step 2 will not execute until step 1 has been completed. In comparison, if we make this asynchronous, and therefore non-blocking, we can execute steps 1 and 2 concurrently. This happens because the event loop will run an iteration of our synchronous code first (step 2), then run our asynchronous code (step 1) - it is changing the order instructions are executed in such a way that our code is non-blocking. Interestingly, this means an asynchronous delay of 0 seconds will run after the next synchronous iteration of code.

Say we introduce step 3, in which we need the response from the API call in step 1. To do this, we can use an async-await, which will be blocking until step 1 completes. This is not purely sequential, as Step 2 does not need to wait for step 1 to complete, but at step 3 we are able to create a synchronous point in our code via async-await. So we are able to keep our code non-blocking where it matters, and still introduce a particular sequence of events.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文