微信小程序tips
# 封装 wx.request
# wx.request 与 requestTask.abort()
const requestTask = wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json'
},
success(res) {
console.log(res.data)
}
})
requestTask.abort() // 取消请求任务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 利用 promise 封装 Request
function request(opt) {
return new Promise((success, fail) => {
const requestTask = wx.request({
...opt,
success,
fail
})
})
}
// usage
request({
url: 'localhost',
signal: signal
})
.then((response) => console.debug(response))
.catch((error) => console.error(error))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 如何封装后取消请求?
function request(opt) {
return new Promise((success, fail) => {
const requestTask = wx.request({
...opt,
success,
fail
})
//
opt.signal && (opt.signal.onabort = () => requestTask.abort())
})
}
// usage
const signal = {}
request({
url: 'localhost',
signal: signal
})
.then((response) => console.debug(response))
.catch((error) => console.error(error))
signal.onabort()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
上次更新: 2023/07/15, 08:37:32