Promise then和async/await处理小程序回调

小程序的请求接口采用回调的方式进行处理,如果请求过多就会造成嵌套的层级过多,代码可读性变差,想要解决这种问题可以直接使用es6的promise,或者async/await

例如有这样一段代码(现在登录逻辑中wx.loginwx.getUserInfo可分开调用)

wx.login({
  success: function (res) {
    wx.request({
      url: constract.login,
      data: { code: res.code },
      success: function (res2) {
        wx.getUserInfo({
          success: function (res3) {
            wx.request({
              url: constract.register,
              data: data,
              success: function (res4) {
                ...
              }
            })
          },
          fail: function (res5) { //拒绝授权,拿不到token
            ...
          }
        })
      }
    })
  }
})

很明显这种函数可读性很差,现在使用Promise改造一下

首先将请求封装成Promise对象

function login(){
  return new Promise(function(resolve,reject){
    wx.login({
      success: resolve,
      fail: reject
    })

  })
}

function getUserInfo(){
  return new Promise(function(resolve,reject){
    wx.getUserInfo({
      success: resolve,
      fail: reject
    })
  })
}

function request(url,method,header,data={}){
  return new Promise(function(resolve,reject){
    wx.request({
      url: url,
      method: method.toUpperCase(),
      data: data,
      header: header,
      success: resolve,
      fail: reject
    })
  })
}

调用

let objArg = {};

login().then(res => { //login API 获取code
  let data = {code: res.code};
  return request(constract.login,'GET',{},data);
})

.then(res2 => { //得到 3rdSession
  objArg.thirdSesson = res2.data.data;
  return getUserInfo();
})

.then(res3 => { // 调用getUserInfo 得到解密参数,授权
  return request(constract.register,'GET',{},{
    thirdSesson:objArg.thirdSesson,
    rawData: res3.rawData,
    signature: res3.signature,
    encryptedData: res3.encryptedData, 
    iv: res3.iv
  })
}).catch(err =>{ //拒绝授权
  return Promise.reject({
    refuseAuth: true,
  })
})

.then(res4 => {

})
.catch(err => { // 错误处理 and 未授权处理
  console.log(err);

  if(err.refuseAuth){
    request(constract.noauthorize,'GET',{},{thirdSesson: objArg.thirdSesson}).then(res6=>{
      token = res6.data.data;
      wx.setStorageSync('token', token);
      typeof dl == "function" && dl(token);
    }).catch(err=>{
      console.log(err);
    })
  }
})

这种方法明显比直接回调更具可读性,在小程序框架wepy中直接使用async/await进行处理

sleep (s) {
   return new Promise((resolve, reject) => {
     setTimeout(() => {
       resolve('promise resolved')
     }, s * 1000)
   })
 }

async testAsync () {
   const data = await this.sleep(3)
   console.log(data)
}

你可能感兴趣的:(小程序)