简体   繁体   English

异步 Promise 阻塞 DOM

[英]Asynchronous Promise blocking DOM

Asynchronous Promises aren't working as I expected in React (specifically React, but I think this will apply to other scenarios).异步 Promise 在 React 中没有像我预期的那样工作(特别是 React,但我认为这将适用于其他场景)。 They still seem to be blocking the main thread, essentially freezing my browser.他们似乎仍然阻塞了主线程,基本上冻结了我的浏览器。

I've got this method that handles a button click:我有这个处理按钮点击的方法:

 onClick() { console.time('factorial') factorial(8000) // factorial is the culprit! .then(n => this.setState({ n })) console.endTime('factorial') }

factorial returns a promise, and so, as expected, I get factorial: 2ms in the console. factorial返回一个承诺,因此,正如预期的那样,我在控制台中得到了factorial: 2ms However, the webpage hangs.但是,网页挂起。 This is also evident when taking a look at the performance metrics:在查看性能指标时,这一点也很明显:

承诺回调需要 700+ 毫秒,阻塞 DOM

The Promise takes 700+ ms to evaluate, and for the entire duration, the DOM seems to be blocked. Promise 需要 700 多毫秒来评估,并且在整个持续时间内,DOM 似乎被阻塞了。 This completely confuses me, since I would expect the DOM to carry on.这完全让我感到困惑,因为我希望 DOM 能够继续。 How can I get my factorial function to not block the DOM?如何让我的factorial函数不阻塞 DOM?

Asynchronous functions are not threads.异步函数不是线程。

They get paused and put in the background while they are waiting for something outside the JavaScript event loop to happen (like an HTTP response to arrive).当它们等待 JavaScript 事件循环之外的事情发生时(例如 HTTP 响应到达),它们会被暂停并置于后台。

While they are running, they are still running, and tie up the event loop like any other function.当它们运行时,它们仍在运行,并且像任何其他函数一样占用事件循环。

If you want to shunt some processing off to another thread, you'll need to use Web Workers .如果你想将一些处理分流到另一个线程,你需要使用Web Workers (At least in the context of a web browser; Node has Worker Threads ). (至少在 Web 浏览器的上下文中;Node 有Worker Threads )。

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

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