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

问题描述

我不明白如何使用异步函数.

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

异步函数 foo() {为了 (;;) {}}富();
解决方案

async 关键字,并承诺在一般情况下,不要使同步代码异步、运行缓慢的代码快速或阻塞代码非-阻塞.

你的函数开始一个循环,然后循环往复.

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

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

只是来来去去.

如果您实际上在循环中一些计算量很大的事情并且您想将其推入后台,那么您可以使用 Node.js Worker Thread 或基于浏览器的 Web Worker 来做.

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