1 async await 的执行
1.1 await 后面的值为普通值
当 await 后面的值为普通值时,会直接返回该值
async function test() {
const res = await 'a'
console.log(res) // a
}
test()
1.2 await 后面的值为 Promise 对象
当 await 后面为 Promise 对象时,会将 resolve的 值直接返回
async function test() {
const res = await new Promise((resolve,reject) => {
console.log('b') // b
resolve('c')
})
console.log(res) // c
}
test()
当 Promise 状态为 reject,如果不使用 try catch 会直接报错,下面的函数不会再执行,会将 reject 的值直接返回给 catch(e)函数
async function test() {
try {
const res = await new Promise((resolve, reject) => {
console.log('b')
reject('c')
})
console.log('d') // 不执行
} catch (e) {
console.log(e)
}
}
test()
2 await 后面函数的执行顺序
2.1 await 后面为普通值
async function test() {
try {
const res = await new Promise((resolve, reject) => {
console.log('b')
reject('c')
})
} catch (e) {
console.log(e)
}
}
test()
执行结果为 1 5 2 6 3 4
当执行函数时,遇到 await,会跳出函数,继续往下执行,当函数外的代码执行完毕后,会执行 await 后面的代码
首先打印 1, 然后 5, 执行 test() 打印 2,遇到 await 跳出函数,打印 6,此时外面代码执行完毕,继续执行 await 后面的代码,打印3,最后打印 4
2.2 await 后面为普通函数
async function test() {
console.log(1)
const res = await test2()
console.log(res)
console.log(2)
}
test()
console.log(4)
function test2() {
console.log(3)
return 5
}
执行结果为 1 3 4 5 2 首先执行 test(), 打印 1,遇到await,await后面为函数,执行该函数,打印 3,该函数返回5, 跳出test函数,打印 4,外面代码执行完毕,回到await函数继续执行,此时打印5,然后打印2
await 执行顺序 由下到上,由内到外
async function test() {
console.log(1)
const res = await test2()
console.log('flag')
console.log(res)
console.log(2)
}
test()
console.log(4)
test2()
console.log('aa')
async function test2() {
console.log(3) //
let res = await test3()
console.log(res)
return 5
}
async function test3() {
console.log(6)
return 7
}
执行结果:1 3 6 4 3 6 aa 7 7 flag 5 2 首先执行test(),打印 1, 遇到await,执行test2()[第一个],打印 3,遇到await,执行test3()[第一个],打印 6,跳出test3()[第一个],跳出test2[第一个],打印 4
执行test2()[第二个],打印 3,遇到await,执行test3()[第二个],打印 6,跳出test2[第二个],打印 aa
此时回到第二个test2函数中的await,第二个test3返回7,因此 打印7[第二个test2] 此时回到第一个test2,第一个test3执行完,返回7,第一个test2打印7,返回5,第一个test2执行完毕,回到test函数中执行,打印 flag,打印 5,打印 2