1.前言
微信小程序API 【 wx.login、wx.request、wx.getUserInfo、wx.getSetting、等 】都有success 和 fail 回调方法结论得出 可通过代理模式+Promise封装
2.实现思路
/**
* @author 栾树
* @date 2021-03-31
* @description { 代理模式 } 思路借鉴 7七月
* @param {Function} fn 微信小程序API (wx.login、wx.request、wx.getUserInfo、wx.getSetting) 等
*/
const promisic = (fn) => {
return (params = {}) => {
return new Promise((resolve, reject) => {
const args = Object.assign(params, {
success: (data)=>resolve(data),
fail: (error)=> reject(error)
})
// 通过代理模式 调用微信API接口
fn(args);
})
}
}
// 导出
export {
promisic
}
3.使用
import { promisic } from './proxy';//方法在proxy文件中 导出方法使用
// 例如我们日常接口调用 wx.request
class User {
async getList() {
const res = await promisic(wx.request)({
url: "https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html",
data: {
author: '栾树',
age: 24
}
})
return res;
}
}