LinUI学习4 Promistic使异步转同步

LinUI学习4 Promistic使异步转同步

在小程序编写的过程中,很多请求都是异步的,因此我们需要将异步转为同步,但是callback太过于繁琐,因此可以将其替换为async和await方式。(需要注意的是,async和await是ES7的语法,在小程序开发工具中需要打开增强编译)

1、封装Promistic

在utils文件夹下新建util.js文件,直接将代码复制进去即可

const promistic = function (func) {
  return function (params = {}) {
    return new Promise ((resolve,reject) =>{
      const args = Object.assign(params,{
        success:(res) =>{
          resolve(res);
        },
        fail: (error) =>{
          reject(error);
        }
      });
      func(args);
    });
  };
};
export{
  promistic
}

2、对之前封装的基础的http请求进行改造

示例:

import { promistic } from "./util"

const {
  config
} = require("../config/config")

class  Http {
  static async request({url, data, method = 'GET'}) {
  const res =  await promistic(wx.request)(
      {
        url:`${config.apiBaseUrl}${url}`,
        data,
        method,
        header: {
          appkey: `${config.appkey}`
        },
      }
    )
    return res.data  //一定不要忘记return
  }
  
}
export{
  Http
}

3、对之前封装的具体http请求进行改造

示例:

import { Http } from "../utils/http"

class Theme{
  static async  getHomeLocationA(){
   const data = await Http.request({
      url:`theme/by/names`,
      data:{
        names:'t-1'
      },
  
    })
    return data  // 一定要记得return
  }
}
export{
  Theme
}

4、调用封装好的http请求

示例:

  onLoad: async function (options) {
   const data = await Theme.getHomeLocationA()
   this.setData({
     topTheme:data[0]
   })
  },

这里需要注意的是,onload内部使用了await 因此 在onload的function前需要添加async 否则会报错

总结:使用pormistic函数可以将所有小程序自带的异步转为同步,

函数内层出现await,则外部必须带一个async

原文地址:https://www.cnblogs.com/mrkr/p/14300979.html