promise async await

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中的异步发送 selectupdate命令到数据库,首先返回的是select,因为查询相对较快,所以要使用asyncawait配合使用.
在需要执行先更新再查询的逻辑时要特别注意

踩坑复现:

    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结果后返回

原因是虽然给getEventListupdateEvent加上了同步限制,但是在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结果先返回

猜你喜欢

转载自blog.csdn.net/claroja/article/details/113836435