微信小程序优化(ES7解决原生API陷入回调地狱)

项目场景:

最近回去维护前段时间写的微信小程序的时候发现一个问题,微信小程序的原生API都是回调函数,那同时使用多个就会陷入回调地狱,代码结构冗杂、难以维护


问题描述:

1.请求业务代码冗杂
请添加图片描述
2.内置api陷入回调地狱
请添加图片描述
3.其他…


解决方案:

请添加图片描述

  • util.js
const promisic = 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 {
  promisic
};
  • http.js
import {
  config
} from "../config/config";
import {
  promisic
} from "./util";

class Http {
  static async request({
    url,
    data,
    method,
    header
  }) {
    const res = await promisic(wx.request)({
      url: `${config.apiBaseUrl}${url}`,
      data,
      method,
      header
    })
    return res.data
  }
}

export {
  Http
}
  • config.js
const config = {
  apiBaseUrl: "https://******/api/v1/",
  form_header: {
    "content-type": "application/x-www-form-urlencoded",
  },
  json_header: {
    "content-type": "application/json",
  }
}

export {
  config
}
  • network.js
import { config } from "../config/config";
import {
  Http
} from "../utils/http";

class Network {
  static async getHomeLocationA(zh,mm) {
    return await Http.request({
      url: `admin/admin_login`,
      method: 'POST',
      header: config.form_header,
      data: {
        zh: zh,
        mm: mm
    }

    })
  }
}

export {
  Network
}
  • index.js
import { Network } from "../../model/network";
// pages/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    const data = await Network.getHomeLocationA('2683070430', '123456789')
    console.log(data)
  },

请添加图片描述

Tip:

因为上述的代码使用代理模式封装请求,原生api支持promise,微信开发者工具不支持部分语法,需要开启增强编译,高版本开发工具直接勾选下面这个选项,增强编译已经合并。请添加图片描述

author: KK
time :2021年9月29日13:27:26
flag:7/30

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值