JavaScript:异步函数是否创建新线程? [英] JavaScript: Does an async function create a new thread?

查看:80
本文介绍了JavaScript:异步函数是否创建新线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mozilla在 XMLHttpRequest 上的文档在 async 参数上包含以下内容:

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

注意:主线程上的同步请求很容易破坏用户体验,应该避免;实际上,许多浏览器已完全弃用主线程上的同步XHR支持.

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.

如果我创建一个包含usng XMLHttpRequest async 函数,那该作为新线程吗?

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

我了解 fetch(),了解Promise,也了解将 XMLHttpRequest 与回调一起使用.这个问题与 async 关键字有关.

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

推荐答案

JavaScript(在浏览器中)完全是单线程的(WebWorkers除外).异步"一词不一定与多线程有关.

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.

网络获取可能会在浏览器网络"线程上以更高性能的语言(C ++,Rust等)发生,但这对JavaScript毫无意义.

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

用JavaScript术语来说,同步的意思是,处理实际网络请求的c ++代码将暂停JavaScript事件循环,直到请求完成为止.这意味着在请求完成之前,在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.

因此,异步意味着您可以在后台进行网络获取的同时,在单个JavaScript线程上执行其他操作.通过c ++调用JavaScript回调或解析JavaScript Promise(又名async/await),可以简化此操作.

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

这篇关于JavaScript:异步函数是否创建新线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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