接触微信小程序有一段时间了,今天简单的用Promise封装了一个wx:request数据请求,分享给大家
//获取实例
const app = getApp()
//用module.exports导出封装的函数 括号里面是参数
module.exports = (url, data, method= "GET", header = {}) =>{
//需要先return一个Promise对象实例
return new Promise((resolve, reject) => {
//微信小程序的数据请求
wx.request({
//'URL'是数据请求地址 url是需要传递的参数
url: 'URL' + url,
data: {
content:data
},
method: method,
header,
dataType: 'json',
success: resolve,
fail: reject
})
})
}
需要引入的页面
//获取应用实例
const app = getApp()
//引入路径地址
const fetch = require('../../utils/fetch.js')
//调用封装好的函数
fetch(`url参数`, { data参数}, )
//成功后的回调
.then((resolve) => {
})
//失败后的回调
.then((reject) => {
}
这样一个简单的wx:request数据请求就封装好了复制代码