async await的提出是用于解决promise产生的回调地狱的。
1、async await需要配合使用,下面是一个简单的例子:
async function a() {
const res = post(url)
console.log(`请求发出后返回的结果是${res}`)
}
2、 但是如果函数体中有一个await语句后面的promise变为reject,那么整个async函数都会中断执行(如上面那个例子),我们希望即使前一个异步操作失败,也不要中断后面的异步操作,一般会有以下几种方法:
方法1:将reject方法写入try...catch内
async function a() {
try {
await Promise.reject('error')
} catch(e) {
console.log(e)
}
return await Promise.resolve('success')
}
a().then(res=> console.log(res))
方法2:在reject后添加catch才处理
async function a() {
await Promise.reject('error').catch(e=> console.log(e))
await Promise.resolve('success')
}
a().then(res=> console.log(res))