async-await
async / await 用同步的方式 执行异步操作
async 关键字 用于声明一个异步函数 只有再 async 函数中才能使用 await
async 函数执行完后会返回一个状态为 fulfilled 的 Promise
async function fn () {
return '张三'
}
console.log(fn) // [AsyncFunction: fn]
console.log(fn()) // Promise {<fulfilled>: 10}
await 关键字 用于等待一个操作的完成
只能再 async 函数中使用
await 规定了异步操作只能一个一个排队执行
从而达到 用同步的方式 执行异步操作
async function fn() {
const res1 = await request1()
console.log(res1) // 此时 如果 request1 报错了 会阻断代码执行
const res2 = await request2(res1)
console.log(res2)
}
错误捕获
try catch
async function fn () {
try {
const res = await request()
}catch(error) {
console.dir('出错了', error)
}
}
如果面对多个 await
async function () {
const res1 = await request1().catch(error => console.log('捕获错误,request1'))
// 此时 request1 出错了不会影响代码执行
const res2 = await request2().catch(error => console.log('捕获错误,request2'))
}
async function f () {
await Promise.reject('error')
//后续代码不会执行
console.log(1)
await 100
}
// 修改后
async function f () {
await Promise.reject('error').catch(err => {
console.log('出错了')
})
//后续代码继续执行
console.log(1)
await 100
}
并发
需要同时发送多个请求
也可以使用 axios.all
async function () {
Promise.all([
await request1()
await request2()
]).then(res => console.log(res))
}
finally
不管promise最后的状态,在执行完then或catch指定的回调函数以后,都会执行finally方法指定的回调函数。
例如可用于关闭加载层