1.当异步函数嵌套到别的函数内后,需要循环使用async和await
否则就会变成异步
async getEventList () {
const {
data: res } = await this.$http.get('/events')
this.eventList = res
},
async updateEvent () {
await this.$http.post('/events/update', this.currentEvent)
},
async finish () {
await this.updateEvent()//等待异步执行完
await this.getEventList()//等待异步执行完
}
2.SQL中的异步发送 select
和update
命令到数据库,首先返回的是select
,因为查询相对较快,所以要使用async
和await
配合使用.
在需要执行先更新再查询的逻辑时要特别注意
踩坑复现:
async getEventList () {
const {
data: res } = await this.$http.get('/events')
this.eventList = res
},
async updateEvent () {
await this.$http.post('/events/update', this.currentEvent)
},
finish () {
this.updateEvent()
this.getEventList() // ??这个bug是什么原因
},
当调用finish
函数时,数据库首先返回了getEventList
的结果,然后返回updateEvent
的结果:
[Event{
id=1, name='ps学习',}, Event{
id=2, name='ps学习', }] //getEventList结果先返回
Event{
id=1, name='ps学习',}//updateEvent结果后返回
原因是虽然给getEventList
和updateEvent
加上了同步限制,但是在finish
外层函数中却没有限制,所以还是异步调用,要改成
async finishStudy () {
await this.updateEvent()
this.studyDialogVisible = false
await this.getEventList() // ??这个bug是什么原因
},
这样返回的结果就正常了
Event{
id=1, name='ps学习',}//updateEvent结果后返回
[Event{
id=1, name='ps学习',}, Event{
id=2, name='ps学习', }] //getEventList结果先返回