app.js和第一个页面是异步执行的吗
我简单说明一下,我在app.js里的onLaunch方法里写了一个请求,在执行的第一个页面(由json定义的第一个页面)的加载页面函数写了一个console.log( res);,然后我经过多次执行发现,有时候是app.js先执行完成,有什么是首页的先执行,并不是我以为的要app.js先执行完成后才执行首页的。有什么办法可以让它先执行完app.js的代码然后再执行首页的吗
我简单说明一下,我在app.js里的onLaunch方法里写了一个请求,在执行的第一个页面(由json定义的第一个页面)的加载页面函数写了一个console.log( res);,然后我经过多次执行发现,有时候是app.js先执行完成,有什么是首页的先执行,并不是我以为的要app.js先执行完成后才执行首页的。有什么办法可以让它先执行完app.js的代码然后再执行首页的吗
helper.js,想需要你自己创建啊。
我这边给你写一个简单的案例吧。
文件一 app.js
//app.jsApp({ onLaunch: function () { }, cache: { getuserid: function () { return wx.getStorageSync('loginuserid'); } }, wx:{ request_post: function (url, data) { return new Promise(function (resolve, reject) { wx.request({ url: url, data: data, method: 'POST', header: { "Content-Type": "application/x-www-form-urlencoded" }, success: function (res) { resolve(res) }, fail: function (err) { reject(err) } }); }); } }}) |
文件二 helper.js
//utils/helper.jsvar app = getApp();function weixinauth() { return new Promise(function (resolve, reject) { if (app.cache.getuserid() > 0) { resolve("无需登录") } else { wx.login({ success: function (res) { if (!res.code) return; //################################## app.wx.request_post('https://api.xxx.com/api/weixin/auth', { code: res.code, }).then(function (res) { wx.setStorageSync("loginuserid", res.data.userid); resolve(res.data) }).catch(function (err) { reject(err.data) }) //################################## } }); } //################################## });}module.exports.weixinauth = weixinauth; |
文件三 index.js-------就是需要登录页面的调用
// pages/index.jsvar helper = require("../utils/helper.js")var that;var app = getApp();Page({ data: { }, onLoad: function (options) { that = this; helper.weixinauth().then(function (resdata) { console.log("resdata"); that.GoLoad(); }).catch(function (errdata) { console.log("errdata"); }) }, GoLoad:function(){ //这里写加载页面的方法 var userid = app.cache.getuserid(); console.log("GoLoad"); }}) |