前言
降低网络请求和 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);
})
}
})