微信小程序的wx.request

微信小程序中的访问以wx.request这个api进行

1
RequestTask wx.request(Object object)

执行后返回一个RequestTask 对象,在使用中如果需要有序的进行多次请求就容易出现多个request嵌套,维护起来非常不便,如下所示,假设有一个api需要在登陆后访问,那么就需要先获取token再访问对应的api:

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
wx.request(
{
// 网络地址
url: "https://url.com/api/atuh",
// 方法
method: "GET",
// 需要传递的数据
data: dataObject,
success: function(res){
if (res.data && res.statusCode == 200) {
wx.request({
url: "https://url.com/api/getsomething",
method: "GET",
header:{
"Content-Type": "application/json",
"Authorization": res.data.token
},
data: dataObject,
success: function(res){
// ...
}
})
}
}
}
)

这里有个坑提示一下,wx.request中只要服务器正常返回任何状态,都会进入success,所以还需要自己在success中检测状态码以及返回数据情况

Promise则可以帮助我们处理这类队列问题

使用Promise

如何创建一个Promise实例

1
2
3
4
5
6
7
8
9
const promise = new Promise(function(resolve, reject) {
// ... 其它代码
//假设异步操作成功
if (true){
resolve(res);
} else {
reject(err);
}
});

resolve以及reject为两个回调函数分别对应操作的成功与失败

包装wx.request

在这里我将创建一个类来把相关的网络访问功能集合在里面

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// utils/webapi.js
class WebApi{
// 构造函数
constructor() {
this.apiServer = "https://url.com/api"
this.authServer = "https://url.com/api/auth"
}
// 单例模式实现
static getInstance() {
if (this._instance == undefined) {
this._instance = new WebApi();
}
return this._instance;
}
// 使用Promise包装一个通用的wx.request方法
request(req) {
return new Promise((resolve, reject) => {
wx.request({
url: req.uri,
method: req.method,
header: req.header,
data: req.data,
success: function (res) {
if (res.data && res.statusCode == 200) {
resolve(res)
} else {
reject(new Error('statusCode : ' + res.statusCode))
}
},
fail: function (res) {
reject(new Error('error'))
}
})
})
}
// 各个API具体调用方法
apiLogin = () => this.request({
uri:`${this.authServer}`,
method: 'GET'})
apiGet = (token, objId) => this.requset({
uri:`${this.apiServer}/get`,
method: 'GET',
header: token,
data: objId
})
}
export default WebApi.getInstance()

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// pages/index/index.js
import myapi from "../../utils/webapi"
Page({
// ... 其它代码
onLoad: function(options){
let objID = 101010
myapi.apiLogin()
.then(
res=> myapi.apiGet(res.data, objID)
)
.then(
res => /* ... 取得第二步操作获得的值,继续执行其它操作 */
)
.catch((err)=>{
// ...这里捕获最后发生的错误
})
}
})

衍生阅读

ECMAScript 6入门 #Promise

ref

Notion