微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐