async & await

async / await 几个重点概念

整理一下 async / await 在使用过程中容易搞不清楚的概念

async function 被调用后会返回一个 promise

1
2
3
4
5
async function say() {

}

say().then().catch()

如果 async function 有 return 值(非 promise.reject),则调用该 function 后返回的 promise 的 resolve 值为该 return 值

1
2
3
4
5
6
7
async function say() {
return 20
return Promise.resolve(20)
}

say().then(res => console.log('res is: ' + res)).catch(err => console.log('err is: ' + err))
// res is 20

如果 async function throw Error,则调用该 function 后返回的 promise 的 reject 值为该抛出值

1
2
3
4
5
6
7
8
9
10
11
function CustomError(msg) {
this.msg = `custom error is ${msg}`
}

async function say() {
throw 42
throw new Error('45')
throw new CustomError('fuck...')
}

say().then(res => console.log(res)).catch(err => console.log(err))

await 关键字用于暂停 async function,等待 promise 的 resolve 值,如果 promise 被 reject,则可在 async function 中 catch

1
2
3
4
5
6
7
8
9
10
11
12
async function say() {
let a
try {
a = await Promise.reject('reject text')
} catch(e) {
a = 'default text'
}
return a
}

say().then(res => console.log('res is: ' + res)).catch(err => console.log('err is: ' + err))
// res is default text