index.js文件引入es6-promise并在onLoad中写下函数:
var Promise = require('../../es6-promise.min.js');//引入ES6
onLoad: function () {
var that = this;
//第一步:更新用户信息
var getUserInfo = function(){
return new Promise(function(resolve,reject){
app.getUserInfo();
resolve();
});
};
getUserInfo().then(function(){
//第二步:其它操作
});
},
并在app.js文件写入下面代码
//app.js
var Promise = require('es6-promise.min.js');//引入ES6
App({
onError:function(res){
console.log(res);
},
//获取session
getSession:function(){
var info=wx.getStorageSync('session');
return info.session;
},
//获取用户信息
getUserInfo:function(){
var timestamp=getTimestamp();//获取当前时间戳
//检查微信登录态是否过期
var checkSession = function(){
return new Promise(function(resolve,reject){
wx.checkSession({
fail: function(){
console.log('SESSION登录态过期!');
reject();
},
success:function(){
resolve();
}
});
});
};
//检查SESSION缓存是否过期
var checkStorage = function () {
return new Promise(function(resolve,reject){
wx.getStorage({
key: 'session',
success: function(res) {
if(res.data.expires){
if(timestamp>res.data.expires){//超时
resolve();
}else{
reject();
}
}else{
resolve();
}
},
fail:function(){
resolve();
}
});
});
};
//刷新用户信息
var updateUserInfo=function(){
return new Promise(function(resolve,reject){
wx.showToast({
title: '加载中',
icon: 'loading',
duration: 10000,
mask:true
});
resolve();
});
}
//用户授权登录
var login= function(){
return new Promise(function(resolve,reject){
wx.login({
success: function(loginRes) {
resolve(loginRes);
},
fail:function(res){
reject(res);
}
});
});
}
//获取用户信息
var getUserInfo = function (loginRes) {
return new Promise(function(resolve,reject){
var that=this;
wx.getUserInfo({
success: function (userinfoRes) {
var data={
loginRes:loginRes,
userinfoRes:userinfoRes
}
resolve(data);
},
fail:function(res){
reject(res);
}
});
});
};
//用户信息入库
var request = function (data) {
return new Promise(function(resolve,reject){
var userInfoStr=JSON.stringify(data.userinfoRes);
wx.request({
url: 'https://www.soswen.com/weixin/Common/getSession',
data: {