嵌套的代码:
wx.request({
url: 'http://se.talelin.com/v1/theme/by/names',
method:'get',
data:{names: 't-1'},
header:{
appkey: '0zvSJQwjpChL8Spo'
},
success:res=>{ //第一次调用成功后,进行第二次调用
console.log('1st request')
wx.request({
url: 'http://se.talelin.com/v1/theme/by/names',
method:'get',
data:{names: 't-1'},
header:{
appkey: '0zvSJQwjpChL8Spo'
},
success:re=>{ //第二次调用成功后赋值
console.log('2nd request')
this.setData({
topTheme: re.data[0]
})
}
})
}
})
使用promise后(这里没有封装wx.request,单纯使用promise)
写法一:
var promise1 = new Promise(function(resolve,reject){
wx.request({
url: 'http://se.talelin.com/v1/theme/by/names',
method:'get',
data:{names: 't-1'},
header:{
appkey: '0zvSJQwjpChL8Spo'
},
success:res=>{
console.log('1st request')
resolve(res)
}
})
})
var promise2 = new Promise(function(resolve,reject){
wx.request({
url: 'http://se.talelin.com/v1/theme/by/names',
method:'get',
data:{names: 't-1'},
header:{
appkey: '0zvSJQwjpChL8Spo'
},
success:re=>{
console.log('2nd request')
resolve(re)
}
})
})
//常见两个promise对象后,引入这两个对象
promise1.then(res => {
promise2.then(re => {
this.setData({
topTheme: re.data[0]
})
})
})
写法二:
上面执行两个promise对象时,还是写成了嵌套的格式,依旧凌乱,可以写成链式的调用
promise1.then(res => {
return promise2
}).then(re => {
this.setData({
topTheme: re.data[0]
})
})