异步Promise阻止DOM [英] Asynchronous Promise blocking DOM

查看:147
本文介绍了异步Promise阻止DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异步承诺不能按我期望的那样工作(特别是React,但是我认为这将适用于其他情况).他们似乎仍然阻塞了主线程,本质上冻结了我的浏览器.

Asynchronous Promises aren't working as I expected in React (specifically React, but I think this will apply to other scenarios). 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返回一个promise,因此,正如预期的那样,我在控制台中得到了factorial: 2ms.但是,该网页挂起.在查看性能指标时,这也很明显:

factorial returns a promise, and so, as expected, I get factorial: 2ms in the console. However, the webpage hangs. This is also evident when taking a look at the performance metrics:

Promise需要700毫秒以上的时间来评估,并且在整个持续时间内,DOM似乎都被阻止了.这完全使我感到困惑,因为我希望DOM能够继续下去.如何获得factorial函数以不阻止DOM?

The Promise takes 700+ ms to evaluate, and for the entire duration, the DOM seems to be blocked. This completely confuses me, since I would expect the DOM to carry on. How can I get my factorial function to not block the DOM?

推荐答案

异步函数不是线程.

当他们等待JavaScript事件循环之外的事件发生时(例如到达HTTP响应),他们会暂停并进入后台.

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).

当它们正在运行时,它们仍在运行,并且像其他任何函数一样捆绑事件循环.

While they are running, they are still running, and tie up the event loop like any other function.

如果您希望将某些处理分流到另一个线程,则需要使用网络工作者. (至少在Web浏览器的上下文中; Node具有 Worker线程).

If you want to shunt some processing off to another thread, you'll need to use Web Workers. (At least in the context of a web browser; Node has Worker Threads).

这篇关于异步Promise阻止DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆