async和await

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'
  })
}
複製代碼
相關文章
相關標籤/搜索