JavaScript: Does an async function create a new thread?

ぃ、小莉子 提交于 2021-02-11 13:52:48

问题


Mozilla’s documentation on XMLHttpRequest includes the following on the async parameter:

Note: Synchronous requests on the main thread can be easily disruptive to the user experience and should be avoided; in fact, many browsers have deprecated synchronous XHR support on the main thread entirely.

That makes sense, as you don’t what to hold up the main thread waiting for an indeterminate period of time.

If I create an async function which includes usng XMLHttpRequest, would that qualify as a new thread?

I know about fetch(), I know about promises, and I know about using XMLHttpRequest with callbacks. This question is about the async keyword.


回答1:


JavaScript (in the browser) is entirely single-threaded (with the exception of WebWorkers). The term "asynchronous" doesn't necessarily have anything to do with being multi-threaded.

The network fetch likely happens on browser "networking" thread in a higher performance language (c++, rust, etc.), but this means nothing to JavaScript.

What synchronous means in JavaScript terms is that the c++ code that handles the actual network request will pause the JavaScript event loop until the request completes. That means absolutely nothing can happen in the JavaScript context until the request finishes.

Therefore async means that you can do other things on the single JavaScript thread while the network fetch happens in the background. This is facilitated by c++ calling a JavaScript callback or resolving a JavaScript Promise (aka async/await).

I will try to elaborate more clearly in pseudocode:

const response = makeRequest({ asyncMode: false });
//nothing can happen until this request finishes
//requestAnimationFrame animation code or click event listeners will not run
// until the request is finished
makeRequest({ asyncMode: true, callback: function(response, error){ console.log("this will execute later once the network request is made") } });
console.log("this code will run right away");
//requestAnimationFrame animation code or click event listeners will run as normal
//  during the request


来源:https://stackoverflow.com/questions/61133976/javascript-does-an-async-function-create-a-new-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!