idiot

小程序中请求同步的问题

2019-11-19

在小程序中会频繁遇到请求数据,而直接用默认的wx.request显然太过繁琐且杂乱…之前是随手把重复的header,url等属性设置提取出来做的简单封装,使用过程中发现还是缺点意思(够龙鸣=) 看不下去了又重新写了一份

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
myRequest: function(url, data, type, success,fail) {
if (type == '' || type == null) {
type = 'JSON';
}
wx.request({
header: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
},
url: url,
data: data,
type: type,
success: success,
fail:fail
})
}

确实够憨了=

小改进

要处理回调嘛,还是用promise吧

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
syncRequest: function(url, data, method) {
var self = this;
var header = {
'content-type': 'application/json'
}
if (method == '' || method == undefined || method == null || method == 'GET' || method == 'get') {
method = 'GET';
} else if (method == 'POST' || method == 'post') {
header = {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
};
}
return new Promise(function(resolve, reject) {
wx.request({
header: header,
url: self.globalData.url + url,
data: data,
type: 'JSON',
method: method,
success: function(res) {
resolve(res);
},
fail: function(res) {
reject(res);
},
})
})
},

暂时就这样吧。