阻塞失效?
考慮下面的語句塊
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后才算異步代碼完成,才可以繼續下面的代碼。
