es6 async 總結

//1 async 返回一個promise對象因此能夠經過.then來調用

async function test1() {
return "測試數據"
}
test1().then((e)=>{
console.log(e) // 測試數據
});


//2 async 裏面若是遇到 return 會直接返回傳到then裏面,不執行後面代碼模塊了

async function test2() {
return "測試數據2";
console.log(1) //不會執行
}
test2().then((e)=>{
console.log(e) // 測試數據
});


//3 await 後面函數若是不是promise對象是個普通函數,而普通函數裏面包含一個異步,await不會等這個異步執行完。

function test3(){
setTimeout(function () {
console.log(1)
},1000)
}
async function test_3() {
await test3();
console.log(2)
}
test_3() //2 1 先輸出2 後輸出1


//4 用try語句能夠防止await異步失敗影響後面代碼執行。

function test_4a() {
return new Promise((resolve,reject)=>{
console.log(1);
resolve(1)
})
}
function test_4b() {
return new Promise((resolve,reject)=>{
console.log(2);
reject()
})
}
async function test4() {
try {
await test_4b();
await test_4a();
} catch (e) {

}

}
test4() // 1
相關文章
相關標籤/搜索