这是我参与8月更文挑战的第21天,活动详情查看:8月更文挑战 !
定义
用同步思维解决异步问题的方案
-
async作为一个关键字放到函数前面
- 任何一个
async
函数都会隐式返回一个promise
- 任何一个
-
await
关键字只能在使用async
定义的函数中使用- await后面可以直接跟一个 Promise实例对象
- await函数不能单独使用
-
async/await 让异步代码看起来、表现起来更像同步代码
用法
await 放置在Promise调用之前,await 强制后面点代码等待,直到Promise对象resolve,得到resolve的值作为await表达式的运算结果
await只能在async函数内部使用,用在普通函数里就会报错
async function a(){
console.log('a');
var a = await b(); //当await返回非promise
console.log('12');
}
function b(){
console.log('b');
} //返回undefined
a();
async 的作用
async 函数负责返回一个 Promise 对象如果在async函数中 return 一个直接量,
async 会把这个直接量通过Promise.resolve() 封装成 Promise 对象;
如果 async 函数没有返回值,它会返回 Promise.resolve(undefined)
await作用
如果await等到的不是一个promise对象,那跟着的表达式的运算结果就是它等到的结果
如果是一个promise对象,await会阻塞后面的代码,等promise对象resolve
async await函数错误处理的方式
1.使用try…catch语句
2.在await后的Promise添加catch回调
和promise相比的优点
1.串行的同步写法,代码阅读相对容易
2.Async/Await让try/catch可以同时处理同步和异步错误。
3.处理复杂流程时,在代码清晰度方面有优势
// 获取栏目和平台列表
getAllCategory() {
allAppConfig().then((pt) => {
this.allAppList = pt.response
this.ptName = pt.response[0].name
this.ptId = pt.response[0].id
getCopyCategory({ appId: this.ptId }).then((lm) => {
this.getAllCategoryList = lm.response
this.lmName = lm.response[0].categoryName
this.categoryId = lm.response[0].categoryId
this.getArticleList()
})
})
}
改为:
async getAllCategory() {
let pt = await allAppConfig()
if (pt.code === 200) {
this.allAppList = pt.response
this.ptName = pt.response[0].name
this.ptId = pt.response[0].id
}
let lm = await getCopyCategory({ appId: this.ptId })
if (lm.code === 200) {
this.getAllCategoryList = lm.response
this.lmName = lm.response[0].categoryName
this.categoryId = lm.response[0].categoryId
}
this.getArticleList()
}