[英]JavaScript Async/Await logic behaving as synchronous
如果我理解正確,用關鍵字async聲明的 function 應該返回 promise。在async3 function 的情況下,我們有 10 億次迭代,這使得返回值需要更長的時間。 分析下面的代碼,我預計會發生的事情是,通過調用sync1和sync2 function,立即登錄控制台,稍后,async3 function 日志會出現。 但是,我注意到sync1和sync2函數僅在async3結束后才記錄。 async3 function難道不應該在另一個線程上或事件循環之外運行,而不會阻止在運行時調用的其他函數的執行嗎?
function sync1() { console.log(1); } function sync2() { console.log(2); } async function async3() { let iteration = 0; let number = 0; while (iteration <= 1000000000) { number = iteration; iteration++; } return number; } sync1(); sync2(); async3().then((val) => console.log(val));
你能解釋一下為什么它會這樣嗎? 我錯過了什么?
我期望的是:
sync1(); // console logged immediately
sync2(); // console logged immediately
async3().then((val) => console.log(val)); // console logged moments later
目前正在發生的事情:
sync1(); // console logged after async3 is done sync2(); // console logged after async3 is done async3().then((val) => console.log(val)); // console logged after async3 is done
請記住 JavaScript 基本上是單線程的。
盡管async3
是異步的,但它的操作完全是同步的,並且是 CPU 密集型的。 一旦瀏覽器有一點空閑時間,output 只會(視覺上)打印到控制台,但以下塊:
while (iteration <= 1000000000) {
number = iteration;
iteration++;
}
在完成上述計算之前,不會讓瀏覽器有空閑時間。
對於sync1
和sync2
立即記錄,一種解決方案是讓async3
每 100,000 次迭代(或其他)暫停,並等待setTimeout
,從而讓瀏覽器有機會做一些事情,比如向控制台顯示內容,處理其他事件監聽器,渲染變化,等等。
另一種解決方案是在worker中執行計算量大的async3
function,它位於單獨的線程上,不會阻塞瀏覽器的主線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.