微信小程序 使用Promise封装wx.request

wx.request

微信小程序原生的网络请求API

1
2
3
4
5
6
7
8
9
10
11
12
13
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success: function(res) {
console.log(res.data)
}
})

Promise

使用Promise封装wx.request,在发起一个请求之前使用wx.showToast(),在接口调用结束的complete回调函数中使用wx.hideToast()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const wxRequest = (params = {}, url) => {
wx.showToast({
title: '加载中...',
icon: 'loading',
duration: 5000
})
let data = params.query || {};
return new Promise((resolve, reject) => {
wx.request({
url: url,
method: params.method || 'GET',
data: data,
header: { 'Content-Type': 'application/json' },
success: res=> {
if (res.data.status == 'success') {
resolve(res.data)
} else {
reject(res.msg)
}
},
complete:()=>{
wx.hideToast()
},
error: e=> {
reject(e)
}
})
})
}
module.exports = {
wxRequest,
}

如何使用

编写一个项目的时候,最好把所有的API接口集合一个js文件中

1
2
3
4
5
6
7
8
9
10
11
12
const http = require("../utils/http.js")
const baseUrl = 'http://127.0.0.1:8888/Wxxcx'

const getUnionId = (params) => http.wxRequest(params, `${baseUrl}/getWxUserInfo`)
const getLatLng = (params) => http.wxRequest(params, `${baseUrl}/getStationList`)
const getOil = (params) => http.wxRequest(params, `${baseUrl}/getOilGun`)

module.exports = {
getUnionId,
getLatLng,
getOil
}

接着,在pages中对应页面的js文件中引入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const api = require('../../api/api.js')
在对应的生命周期函数中写入

api.getUnionId({
query: {
code: app.globalData.code,
iv: res.iv,
encryptedData: res.encryptedData
}
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})

参考资料

  1. 微信小程序
  2. ECMAScript 6 入门