util.js
var Promise = require('bluebird.js')
function wxPromisify(fn) {
return function (obj = {}) {
return new Promise((resolve, reject) => {
obj.success = function (res) {
resolve(res)
}
obj.fail = function (res) {
reject(res)
}
fn(obj)
})
}
}
module.exports = {
wxPromisify: wxPromisify
}
index.js
var util = require('../../utils/util.js');
onLoad: function (options) {
var that = this;
uid = wx.getStorageSync('user_id');
if (uid == '') {
var wxLogin = util.wxPromisify(wx.login);
var wxgetUserInfo = util.wxPromisify(wx.getUserInfo);
wxLogin().then(function (res) {
var data = {
code: res.code
};
api._post(api.HOST_URI + 'appletsys/getUserOpenId', data, function (res) {
wx.setStorageSync('openid', res.data.data.openid);
wx.setStorageSync('token', res.data.data.token);
})
}).catch(function (res) {
wx.showToast({
title: '登录失败!',
icon: 'loading',
duration: 1000
})
})
wxgetUserInfo().then(function (res) {
console.log(res);
wx.setStorageSync('icon', res.userInfo.avatarUrl);
wx.setStorageSync('nickName', res.userInfo.nickName);
var data = {
user_nick: res.userInfo.nickName,
icon: res.userInfo.avatarUrl,
openid: wx.getStorageSync('openid'),
token: wx.getStorageSync('token')
}
api._post(api.HOST_URI + 'user/registerUser', data, function (res) {
console.log(res);
wx.setStorageSync('user_id', res.data.data.id);
if (res.data.data.id) {
console.log('注册成功');
}
});
}).catch(function (res) {
wx.showToast({
title: '请重新授权!',
icon: 'loading',
duration: 1000
})
})
}
},