微信小程序 - 网络请求(wx.request)封装:Promise 获取回调结果及降低微信 API 耦合度

前言

降低网络请求和 wx.request 的耦合度,改用 Promise 的方法获取回调结果。

封装

创建 service.js 文件,写入以下封装好的函数:

// 封装 wx.request
export default function request(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: options.url, //服务器接口地址
      method: options.method || 'GET', //请求方法
      data: options.data || {}, //请求参数
      success: resolve, //接口调用成功回调函数
      fail: reject //接口调用失败回调函数
    })
  })
}

使用

打开 index.js ,引入 → 使用。

//引入request函数;路径使用相对路径
import request from '../service/service.js'
Page({
  onLoad: function() {
    request({
      url: 'http://httpbin.org',
    }).then((res) => {
      console.log(res);
    }).catch((err) => {
      console.log(err);
    })
  }
})

猜你喜欢

转载自blog.csdn.net/weixin_44198965/article/details/108316598
今日推荐