異步代碼async await阻塞進程的誤區——await的是Promise的resolve而不是語句塊的執行結束


阻塞失效?

考慮下面的語句塊

var f = async function(){
	await setTimeout(()=>{console.log(1)}, 3000);
	console.log(2);
}
f();

結果先打印出了2,隨后打印出了1,看似並沒有阻塞等待;然而,殊不知只要setTimeout該函數注冊完成就算該異步代碼完成,可以繼續進行下面的代碼。
下面看一個菜鳥教程教程中的例子

function testAwait (x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}
 
async function helloAsync() {
  var x = await testAwait ("hello world");
  console.log(x); 
}
helloAsync ();

這里等待的(await)就是真正的異步代碼,僅當Promise對象resolve后才算異步代碼完成,才可以繼續下面的代碼。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM