1. When the asynchronous function is nested in other functions, it is necessary to use async and await in a loop,
otherwise it will become asynchronous
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 asynchronous send select
and update
commands to the database, the first returns select
, because the query is relatively fast, so you want to use async
, and await
with the use.
In particular, attention needs to be performed to the first query and then update logic
Stepping on the pit to reproduce:
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是什么原因
},
When the finish
function is called , the database first returns the getEventList
result, and then updateEvent
the result:
[Event{
id=1, name='ps学习',}, Event{
id=2, name='ps学习', }] //getEventList结果先返回
Event{
id=1, name='ps学习',}//updateEvent结果后返回
The reason is that has given getEventList
and updateEvent
added sync limit, but finish
did not limit the outer function, so it is an asynchronous call, I wanted to change
async finishStudy () {
await this.updateEvent()
this.studyDialogVisible = false
await this.getEventList() // ??这个bug是什么原因
},
The result returned in this way is normal
Event{
id=1, name='ps学习',}//updateEvent结果后返回
[Event{
id=1, name='ps学习',}, Event{
id=2, name='ps学习', }] //getEventList结果先返回