小程序中 Promise解决异步执行的问题
2018-05-24 本文已影响444人
super静_jingjing
项目需要获取用户的openid,逻辑是在app.js的onLaunch中调用wx.login方法,success之后wx.request去请求后台获取openid;
获取成功之后在page的onLoad方法中使用;
想的很完美,但是实现时发现,在wx.request还未执行完就执行了page的onLoad;
经过一番挣扎,使用Promise解决了这个问题;贴上代码以示尊重。
app.js
App({
globalData: {
hostUrl: "https://wxapp.becypress.com/"
},
onLaunch: function () {
// 展示本地存储能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
},
getOpenid:function(){
var that = this;
return new Promise(function (resolve, reject){
wx.login({
success: function (res) {
if (res.code) {
//发起网络请求
wx.request({
url: that.globalData.hostUrl + 'wechat/app/login/' + res.code,
data: {
},
success: function (res) {
//resolve到index.js的then中
resolve(res.data.openid);
}
});
} else {
console.log('登录失败!' + res.errMsg)
}
}
});
});
}
})
index.js
var app = getApp();
Page({
data: {
url:""
},
onLoad: function (options) {
var that = this;
app.getOpenid().then(function(openid){
that.setData({
url: app.globalData.hostUrl + "app/index.html?opneid=" + openid
});
});
}
})