小程式開發之解決第一次載入頁面獲取不到openid的問題
阿新 • • 發佈:2019-01-29
記錄:小程式開發過程中,index.wxml載入時需要使用使用者資訊,之前wx.login是寫在app.js的onLaunch函式中,通過後臺獲取到openid後儲存到本地快取中,之後在index.js中獲取openid老是出現第一次取值為空,第二次再開啟就有值的情況。原始碼如下:
app.js:
onLaunch: function () { var that = this wx.login({ success: function (res) { //code 獲取使用者資訊的憑證 if (res.code) { //請求獲取使用者詳細資訊 wx.request({ url: "https://pig.intmote.com/wxApp/user/getOpenid.do", data: { "code": res.code }, method: 'GET', header: { 'Content-type': 'application/json' }, success: function (res) { //儲存openid wx.setStorageSync('openid', res.data.openid);//儲存openid wx.showToast({ title: "登入成功" }) } }); } else { wx.showToast({ title: "登入失敗" }) } } }) },
index.js
onLoad: function () {
var that = this;
wx.showToast({ title: wx.getStorageSync('openid') });
that.setData({
openid: wx.getStorageSync('openid')
})
},
出現這種情況是因為app.js onLaunch是非同步載入,在載入index.js onLoad的時候還沒有取到openid
解決方案:
使用promise來獲取非同步操作的訊息。
Promise簡介
Promise 是非同步程式設計的一種解決方案,所謂Promise ,簡單說就是一個容器,裡面儲存著某個未來才會結束的事件(通常是一個非同步操作)的結果。從語法上說,Promise是一個物件,從它可以獲取非同步操作的訊息。
promise基本用法如下:
const promist = new Promise(function(resolve,reject){
if(/*非同步操作成功*/){
resolve(value);
}else{
reject(error);
}
})
resolve函式的作用是,將Promise物件的狀態從“未完成”變為“成功”,在非同步操作成功時呼叫,並將非同步操作的結果,作為引數傳遞出去;
reject函式的作用是,將Promise物件的狀態從“未完成”變為“失敗”,在非同步操作失敗時呼叫,並將非同步操作報出的錯誤,作為引數傳遞出去。
Promise 例項生成以後,可以用then 方法分別指定resolved狀態和rejected狀態的回撥函式。
promise.then(function(value){
//success
},function(error){
//failure
});
小程式程式碼實現:
1.app.js中定義getOpenid函式,並使用promise生成例項
getOpenid: function () {
var that = this;
return new Promise(function (resolve, reject) {
wx.login({
success: function (res) {
//code 獲取使用者資訊的憑證
if (res.code) {
//請求獲取使用者openid
wx.request({
url: "https://pig.intmote.com/wxApp/user/getOpenid.do",
data: { "code": res.code },
method: 'GET',
header: {
'Content-type': 'application/json'
},
success: function (res) {
wx.setStorageSync('openid', res.data.openid);//儲存openid
var res = {
status: 200,
data: res.data.openid
}
resolve(res);
}
});
} else {
console.log('獲取使用者登入態失敗!' + res.errMsg)
reject('error');
}
}
})
});
},
2.index.js通過promise的then方法取出openid
//獲取應用例項
const app = getApp()
Page({
data: {
openid : '',
},
onLoad: function () {
var that = this;
app.getOpenid().then(function (res) {
if (res.status == 200) {
that.setData({
openid: wx.getStorageSync('openid')
})
} else {
console.log(res.data);
}
});
},
})