promise vs callback
以一个简单的http请求类为例
- 为了更好的显示功能用了两个文件http.js和classic.js
- 异步操作显然剥夺了函数的return能力,通常用回调函数来获取返回的结果,回调函数易于理解,但容易造成callback hell让代码看起来混乱难以理解
- promise(包括promise的语法糖 async await)能很好的解决这个问题。虽然本质上没有区别但是从写法上看promise的这种链式写法显然比一层又一层的回调显得代码简洁和易于理解(有关promise的详解请看下篇)
callback实现
1.http.js
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
31class HTTP {
request ({url, data = {}, method = 'GET',success}) {
wx.request({
url: config.api_base_url + url,
method: method,
data: data,
header: {
'content-type': 'application/json',
'appkey': config.appkey
},
success: (res) => {
let code = String(res.statusCode)
if (code.startsWith('2')) {
// 回调函数
success(res)
} else {
wx.showToast({
// title: res.data ? res.data.msg : '请求异常,请稍后再试',
title: '请求异常,请稍后再试',
icon: 'none',
duration: 3000
})
}
},
fail: (err) => {
wx.showToast({
title: '请求异常,请稍后再试',
})
}
})
}2.classic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class ClassicModel extends HTTP {
getLatest (callback) {
this.request({
url: 'classic/latest',
method: 'GET',
success: (res) => {
callback(res.data)
this._setLatestIndex(res.data.index)
}
})
}
_setLatestIndex(index) {
wx.setStorageSync('latestIndex', index)
}
}
promise实现
1.http.js
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
34class HTTP {
request ({url, data = {}, method = 'GET'}) {
const promise = new Promise((resolve, reject) => {
wx.request({
url: config.api_base_url + url,
method: method,
data: data,
header: {
'content-type': 'application/json',
'appkey': config.appkey
},
success: res => {
let code = String(res.statusCode)
if (code.startsWith('2')) {
resolve(res)
} else {
wx.showToast({
// title: res.data ? res.data.msg : '请求异常,请稍后再试',
title: '请求异常,请稍后再试',
icon: 'none',
duration: 3000
})
}
},
fail: (err) => {
wx.showToast({
title: '请求异常,请稍后再试',
})
}
})
})
return promise
}
}2.classic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class ClassicModel extends HTTP {
getLatest () {
const params = {
url: 'classic/latest'
}
return this.request(params).then(res => {
this._setLatestIndex(res.data.index)
return new Promise((resolve, reject) => {
resolve(res.data)
})
})
}
_setLatestIndex(index) {
wx.setStorageSync('latestIndex', index)
}
}