美文网首页
微信小程序 wx.request 全局封装 并使用 Async

微信小程序 wx.request 全局封装 并使用 Async

作者: 张思学 | 来源:发表于2020-03-20 11:04 被阅读0次

之前有写过request封装,本次写一个像 react、vue 一样使用 Async await 的全局封装

  1. 在 utils 文件夹内放入 regeneratorRuntime.js
    如你还不了解 regeneratorRuntime.js 那请看下方文章
    微信小程序 使用 Async await 异步转同步请求

  2. 在 utils 文件夹内新建 api.js

var Api = {
  fetchApi: function(params, method, api_path) {
    let _this = this;
    return new Promise((resolve, reject) => {
      wx.request({
        url: api_path,
        data: Object.assign({}, params.data),
        method: method,
        success: resolve,
        fail: reject
      })
    })
  },
  result: function(params, method, api_path) {
    let _this = this;
    return _this.fetchApi(params, method, api_path).then(res => res);
  }
}
export default Api;
  1. 在 utils 文件夹内新建 request.js 并引入写好的封装方法 api.js
import Api from "./api";
const state = false;  // 环境状态, true正式, false测试
const formal = 'https://www.xxx.com'; // 正式
const test = 'https://test.xxx.com'; // 测试
const http = state ? formal : test; // 最终使用

// 登录
export function getLogin(params) {
  return Api.result(params, 'GET', http + '/api').then(res => res);
}
  1. 在 app.js 添加全局使用
const http = require('./utils/request.js');
App({
  globalData: {
    http, // 全局请求
  },
})
  1. 在你的 要请求接口的 项目文件内引入 regeneratorRuntime 和 getApp() 来使用 api 全局 http 请求,并执行同步 Async await
const regeneratorRuntime = require('../../utils/regeneratorRuntime.js')
const app = getApp();
const $http = app.globalData.http;
Page({
   async getHttp(){
     const params = {
        data: {
          tel: 13333333333
        }
        const { res } = await $http.getLogin(params);
        if (res){
          console.log('成功');
        }
     }  
  }
})

相关文章

网友评论

      本文标题:微信小程序 wx.request 全局封装 并使用 Async

      本文链接:https://www.haomeiwen.com/subject/gmwdyhtx.html