1.async 函數傳回一個promise對象,可以使用then方法添加回調函
async function show() {
return {a:23,b:34}
}
console.log(show()) // //Promise {<fulfilled>: {…}}
show().then(res=>{
console.log('res',res) // res {a: 23, b: 34}
})
2.await 關鍵字存在async函數表達式中,用于等待Promise對象,暫停執行,等到異步操作完成後,恢複async函數的執行并傳回解析值
async function test1() {
console.log('執行')
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('延遲3秒後傳回成功')
resolve({ a: '1' })
}, 3000)
})
}
async function test2() {
let x = await test1()
console.log('x', x)
return x
}
test2().then((res) => {
console.log('res', res)
})
// 執行結果如下
執行
延遲3秒後傳回成功
x { a: '1' }
res { a: '1' }
// 如果屏蔽掉resolve({a: '1'}),僅列印
執行
延遲3秒後傳回成功
3.如果是普通函數就不會等待執行,而是直接執行await後面的語句
async function test3() {
setTimeout(() => {
console.log('普通函數')
})
}
async function test4() {
await test3()
console.log('直接執行')
}
test4()
// 執行結果
直接執行
普通函數
// 如果去掉延遲函數
async function test3() {
console.log('普通函數')
}
async function test4() {
await test3()
console.log('直接執行')
}
test4()
// 執行結果
普通函數
直接執行
4.捕獲異常
// 傳回的reject狀态被外層的catch捕獲,然後終止了後面的執行。
function testAwait() {
return Promise.reject("error");
}
async function test1() {
await testAwait();
console.log('test1');// 沒有列印
}
test1().then(v=>{
console.log(v)
}).catch(e=>{
console.log(e) // 'erroe'
})
5.try catch 捕獲
function test1() {
return new Promise((resolve, reject) => {
reject("error")
})
}
async function test2() {
try {
await test1()
} catch (e) {
console.log("報錯", e)
}
}
test2().then((res) => {
console.log("執行成功", res) // 列印:執行成功undefined
}).catch(err => {
console.log('err', err)
})
// 列印結果
報錯 error
執行成功 undefined