promise async await

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 selectand updatecommands to the database, the first returns select, because the query is relatively fast, so you want to use async, and awaitwith 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 finishfunction is called , the database first returns the getEventListresult, and then updateEventthe result:

[Event{
    
    id=1, name='ps学习',}, Event{
    
    id=2, name='ps学习', }] //getEventList结果先返回
Event{
    
    id=1, name='ps学习',}//updateEvent结果后返回

The reason is that has given getEventListand updateEventadded sync limit, but finishdid 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结果先返回

Guess you like

Origin blog.csdn.net/claroja/article/details/113836435