如何在小程序中使用async/await

3,770 阅读2分钟

在开发过程中,有很多需求都需是要异步代码同步处理的,我搜了网上的教程,最多的是推荐使用regenerator,但是需要引入第三库,因为懒一直没用,还使用的是Promise,也是最近才得知,在微信开发工具上勾选的增强编译是可以使用asyncawait的,所有就试了一下,真香~

为什么要使用async/await

假设一个需求:有两个两个异步,第一个获取列表,第二个获取列表里的第一个的详情。这时候应该怎么做?

  1. 在第一个请求之后里写第二个请求,这可能是你第一个想法,可是这个深度是5层、10层呢?代码将会变的无法维护,想想都可怕

  2. 使用Promise,使用一直点then。但是如果出现错误,不容易捕捉到。

  3. 最优雅的写法,asyncawait

我们使用 CNode Api 练习,先获取首页文章列表,然后在获取第一个文章的详情。

一、使用Callback


Page({
  onLoad: function () {
    this.ajax1()
  },
  ajax1(){
    const that = this;
    wx.request({
      url: 'https://cnodejs.org/api/v1/topics',
      success:res=>{
        console.log(1, res)
        let firstId = res.data.data[0].id;
        that.ajax2(firstId)
      }
    })
  },
  ajax2(id){
    wx.request({
      url: `https://cnodejs.org/api/v1/topic/${id}`,
      success:res=>{
        console.log(2, res)
      }
    })
  }
})

二、使用Promise

Page({
  onLoad: function () {
    this.ajax1()
      .then(id => {
        return this.ajax2(id)
      }).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
  },
  ajax1() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://cnodejs.org/api/v1/topics',
        success: res => {
          console.log(1, res)
          let firstId = res.data.data[0].id;
          resolve(firstId)
        },
        fail: err => {
          reject(err)
        }
      })
    })
  },
  ajax2(id) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://cnodejs.org/api/v1/topic/${id}`,
        success: res => {
          console.log(2, res)
          resolve(res)
        },
        fail: err => {
          reject(err)
        }
      })
    })
  }
})

对比回调,使用Promise的链式调用就优雅很多了。

三、使用async、await

小程序增强编译:代码增强编译

需要在微信开发者工具中勾选 增强编译

Page({
  onLoad: function () {
    (async ()=>{
      let id = await this.ajax1()
      let res = await this.ajax2(id)
      console.log(res)
    })()
  },
  ajax1() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://cnodejs.org/api/v1/topics',
        success: res => {
          console.log(1, res)
          let firstId = res.data.data[0].id;
          resolve(firstId)
        },
        fail: err => {
          reject(err)
        }
      })
    })
  },
  ajax2(id) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://cnodejs.org/api/v1/topic/${id}`,
        success: res => {
          console.log(2, res)
          resolve(res)
        },
        fail: err => {
          reject(err)
        }
      })
    })
  }
})

参考:微信小程序中使用 async/await的方法实例分析