async和await

269 阅读1分钟

async/await摘要

ES7 提出的async 函数,终于让 JavaScript 对于异步操作有了终极解决方案。No more callback hell。
async 函数是 Generator 函数的语法糖。
await 操作符用于等待一个 Promise 对象, 它只能在异步函数 async function 内部使用.
async function 可以定义一个 异步函数。

使用promise处理异步

getCLubs() {
  this.ajax({
    url: API.CLUBS,
    method: 'get'
  }).then(res => {
    let clubs = res.data
    clubs.map(item => {
      item.sumPriceFormat = this.numberFormat(item.sumPrice / 10000, 2)
    })
    this.clubs = clubs
    this.$apply()
  })
}
onShow() {
  this.getCLubs()
}

使用async/await处理异步

//await只能在asyn函数中使用
async onLoad(options) {
  let res = await this.ajax({
    url: API.CLUBS,
    method: 'get'
  })
}