菜鸟初识Promise,为了解决小程序得的登陆问题,我采用了Promise去保证用户先行登陆,再执行后面的接口操作。最近却出现了问题,之前我都是想都没想 new Promise,今天发现一个问题,then()
调用的函数getClub()中的wx.request发送竟早于最早的Promise对象userlogin()中的wx.request请求发送。
调用代码如下
var that = this;
app.userlogin()
.then(
that.getClub()
)
.then(that.changeclub())
.catch(
(err)=>{
console.log(err)
}
)
app.js 中的函数代码
:
userlogin: function () {
var that = this;
return new Promise(
(resolve,reject) => {
console.log('app.js 登陆函数 开始运行')
wx.showLoading({
title: '登陆中',
})
wx.login({
success: function (res) {
var code = res.code
wx.getUserInfo({
success: function (res) {
that.globalData.userInfo = res.userInfo;
console.log(that.globalData.userInfo)
wx.request({
url: that.login_url,
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: {
code: code,
nickname: res.userInfo.nickName,
gender: res.userInfo.gender,
city: res.userInfo.city,
province: res.userInfo.province,
country: res.userInfo.country,
head: res.userInfo.avatarUrl,
},
method: 'POST',
success(res) {
that.thirdid = res.data.data
wx.setStorageSync('thirdid', res.data.data)
wx.setStorageSync('userInfo', that.globalData.userInfo)
return resolve('app.js login success')
}
})
},
fail: function () {
wx.showToast({
title: '登陆异常',
image: '/image/erro.png'
})
reject('app.js login failed')
}
})
},
fail: function () {
wx.showToast({
title: '登陆异常',
image: '/image/erro.png'
})
reject('app.js login failed')
},
})
}
)
}
回调函数代码
getClub:function(){
console.log('getClub 开始运行');
let thirdid = wx.getStorageSync('thirdid');
let that = this;
wx.request({
url: app.manage_club,
data:{
thirdid:thirdid
},
success(res){
if(res.data.code==200){
that.setData({
club_list:res.data.data
})
console.log('获取社团列表成功')
return
}
else{
return
}
}
})
}
这里getClub的请求发送会早于userlogin()的请求,导致getClub中thirdid undefined。
是不是Promise中的异步请求也必须封装成Promise对象,也就是我必须封装wx.request方法?还是这里代码有问题?
有劳各位大佬指教了,感谢感谢。
.then()
不是那样用的。看你的第一段代码,正确写法是:
你体会一下区别…如果不明白的话我再细讲
这不是 Promise 的知识,是函数传参的知识