1. 含义
目的:简化异步操作 本质:Generator函数的语法糖
将 * 替换成 async 将 yield 替换成 await 向对于Generator的优化
内置执行器,普通函数式调用 语义增强 更广的适应性 返回Promise对象,方便后续操作
2. 基本用法
返回值:Promise对象 await:返回(继续主线程执行),等待异步操作完成后(Promise对象结束)继续
( async ( ) => {
console. log ( 1 )
await new Promise (
resolve=> setTimeout ( resolve, 1000 )
)
console. log ( 3 )
} ) ( )
console. log ( 2 )
3. 语法
返回Promise对象
async函数返回值,是then方法回调函数的参数 async内的错误,可被catch捕获
( async ( ) => 1 ) ( ) . then ( v=> console. log ( v) )
( async ( ) => { throw new Error ( 'err' ) } ) ( )
( async ( ) => { throw new Error ( 'err' ) } ) ( ) . catch ( v=> console. log ( v) )
async返回的Promise,状态改变条件:内部所有Promise执行完毕,或return,或错误 await 命令
后接 Promise对象,返回该对象结果 后接 非Promise对象,直接返回对应的值 后接 thenable对象,视作Promise对象 await在结尾:相当于 return await … reject状态会中断async函数的执行
( async ( ) => console. log ( await Promise. resolve ( 2 ) ) ) ( )
( async ( ) => {
await Promise. reject ( 2 )
} ) ( ) . catch ( v=> console. log ( v) )
( async ( ) => console. log ( await 1 ) ) ( )
async function sleep ( ) {
await new Promise ( resolve=> setTimeout ( resolve, 1000 ) )
}
( async ( ) => {
for ( let i= 0 ; i< 3 ; i++ ) {
console. log ( i)
await sleep ( )
}
} ) ( )
( async ( ) => {
let v1 = await Promise. resolve ( 1 )
console. log ( v1)
let v2 = await Promise. reject ( 2 )
console. log ( '第二个' )
let v3 = await Promise. resolve ( 3 )
console. log ( v3)
} ) ( ) . catch ( v=> console. log ( v) )
( async ( ) => {
let v1 = await Promise. resolve ( 1 )
console. log ( v1)
} ) ( ) . then ( v=> console. log ( v) )
错误处理
await后的异步报错,则async返回rejected的Promise
async function fun ( ) {
try {
await step1 ( )
await step2 ( )
...
} catch ( e) { }
}
使用注意点
await 后 Promise 对象,结果可能是 rejected,最好使用try…catch… 并发逻辑处理 await只能存在于async函数中,否则报错
function sleep ( param) {
return new Promise (
resolve=> setTimeout ( ( ) => {
resolve ( param)
} , 2000 )
)
}
async function fun ( ) {
let a = await sleep ( 1 )
console. log ( a)
let b = await sleep ( 2 )
console. log ( b)
}
async function fun1 ( ) {
let a = sleep ( 1 )
let b = sleep ( 2 )
let r1 = await a
console. log ( r1)
let r2 = await b
console. log ( r2)
}
async function fun2 ( ) {
let rets = await Promise. all ( [ sleep ( 1 ) , sleep ( 2 ) ] )
console. log ( rets)
}
fun ( )
fun1 ( )
fun2 ( )
4. async 函数的实现原理
async function fun ( args) {
}
function fun ( args) {
return spawn ( function * ( ) {
} )
}