admin 管理员组文章数量: 1184232
解决微信小程序 app onLaunch异步请求,在没有请求执行完就加载首页了的问题
今天在调试小程序的过程中,进了一个坑,程序加载需要先获取用户信息,然后保存到Storage中,然后首页去
Storage取信息,根据用户信息去查本地服务器数据列表,可是发现第一次进入的时候,数据总是加载不出来,只有再次进入才有数据。调试之后发现app.js onLaunch并没有先于onLoad 执行完再执行,而是onLoad先执行完,所以第一次进入的时候根本没有Storage,追了下原因是因为wx.login是需要用户授权登录,同时异步加载首页,所以就出现这问题,解决办法
1、加一个启动页,获取成功后,然后再跳转首页;
2、使用promise,判断进程状态,在index中去判断进程状态,再去执行页面的加载。
解释下Promise:
var promise = new Promise(function(resolve, reject) {if (/* 异步操作成功 */){resolve(value);} else {reject(error);}
});promise.then(function(value) {// success
}, function(value) {// failure
});
Promise 构造函数接受一个函数作为参数,该函数的两个参数分别是 resolve 方法和 reject 方法。
如果异步操作成功,则用 resolve 方法将 Promise 对象的状态,从「未完成」变为「成功」(即从 pending 变为 resolved);
如果异步操作失败,则用 reject 方法将 Promise 对象的状态,从「未完成」变为「失败」(即从 pending 变为 rejected)。
贴一下APP.js代码:
//app.js
var http = require('service/http.js')
App({onLaunch: function() {//调用API从本地缓存中获取数据// var that = this;},getAuthKey: function () {var that = this;return new Promise(function (resolve, reject) {// 调用登录接口wx.login({success: function (res) {if (res.code) {that.globalData.code = res.code;//调用登录接口wx.getUserInfo({withCredentials: true,success: function (res) {that.globalData.UserRes = res;that.globalData.userInfo = res.userInfo;that.func.postReq('/api/v1/image/oauth', {code: that.globalData.code,signature: that.globalData.UserRes.signature,encryptedData: that.globalData.UserRes.encryptedData,rawData: that.globalData.UserRes.rawData,iv: that.globalData.UserRes.iv}, function (res) {wx.setStorage({key: "auth_key",data: res.data.auth_key})var res = {status: 200,data: res.data.auth_key}resolve(res);})}})} else {console.log('获取用户登录态失败!' + res.errMsg);var res = {status: 300,data: '错误'}reject('error');} }})});},
})
//index.jsonLoad: function () {app.getAuthKey().then(function (res) {console.log(res);if (res.status == 200){var auth_key = res.data;app.func.req('/api/v1/image/theme-list', {page: 1,auth_key: auth_key}, function (res) {var page = that.data.pageValue + 1;that.setData({images: res.data,pageValue: page});});}else{console.log(res.data);}});
本文标签: 解决微信小程序 app onLaunch异步请求,在没有请求执行完就加载首页了的问题
版权声明:本文标题:解决微信小程序 app onLaunch异步请求,在没有请求执行完就加载首页了的问题 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.roclinux.cn/b/1686652150a20601.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论