问题
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 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:
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?
回答1:
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).
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. (At least in the context of a web browser; Node has Worker Threads).
来源:https://stackoverflow.com/questions/51492263/asynchronous-promise-blocking-dom