本文介绍了为什么异步循环在异步函数中时会被阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白如何使用异步功能.

为什么下面的代码停止主线程?

async function foo() {
  for (;;) {}
}
foo();
解决方案

async关键字通常保证不会使同步代码异步,快速运行慢速代码或阻止代码非阻塞.

async只是使函数返回一个promise,并提供(与await关键字一起)与其他promise进行交互的机制,就像同步了一样.

您的函数开始循环,然后四处循环.

它没有到达函数的结尾,这将结束函数并解决它返回的承诺.

它没有到达await关键字并在等待已解决的诺言时暂停.

恰好四处走动.

如果您实际上是在循环中,这在计算上是昂贵的,并且您想推入后台,那么您可以使用Node.js 工作线程或基于浏览器的网络工作者即可做到.

I don't understand how to work with asynchronous functions.

Why does the code below stop the main thread?

async function foo() {
  for (;;) {}
}
foo();
解决方案

The async keyword, and promises in general, don't make synchronous code asynchronous, slow running code fast, or blocking code non-blocking.

async just makes the function return a promise and provides (with the await keyword) a mechanism to interact with other promises as if there were synchronous.

Your function starts a loop, and then just goes around and around.

It doesn't get to the end of the function, which would end the function and resolve the promise it returned.

It doesn't reach an await keyword and pause while it waits for the awaited promise to be resolved.

It just goes around and around.

If you were actually doing something in the loop which was computationally expensive and you wanted to push off into the background, then you could use a Node.js Worker Thread or a browser-based Web Worker to do it.

这篇关于为什么异步循环在异步函数中时会被阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 03:03