小程序Page里的函數比app.js先執行的解決辦法


問題描述:

當我們初始化一個小程序時,默認文件 app.js 中有onLaunch函數,

onLaunch: function () {
	console.log("onLaunch");
	wx.login({
      success: res => {
        console.log("login");
        // 發送 res.code 到后台換取 openId, sessionKey, unionId
      }
    })
}

默認目錄,"pages/index/index", 中index.js 有 onLoad函數

onLoad: function () {
    console.log("index onLoad");
}

小程序網絡請求默認為異步請求,在app.js的onLaunch運行后進行異步請求時,程序不會停止,index.js頁已執行onload, onload里面的數據會因為沒有獲取到app.js里的東西而報錯, 我們希望onLaunch執行完后再執行onLoad。

他們的執行順序是:
onLaunch > index onLoad > login

我們希望的執行順序是:
onLaunch > login > index onLoad

解決辦法

  1. 定義回調函數, onload里獲取不到東西就一直獲取,不執行下一步操作,直到獲取到app.js的數據才繼續執行。若login返回為空,則給app.js注冊一個loginSuccessCallback回調,這個回調方法的執行時機,就是app.js中的異步請求完畢

  2. 把 app.js 中的 onLaunch 中方法拿到 index.js 文件中,按照自己的邏輯寫

  3. 使用promise

方法1:

App({
  onLaunch: function () {
    wx.login({
      success: res => {
        this.globalData.checkLogin = true;
        //由於這里是網絡請求,可能會在 Page.onLoad 之后才返回
        // 所以此處加入 callback 以防止這種情況
        if (this.checkLoginReadyCallback){
          this.checkLoginReadyCallback(res);
        }
      }
    })
  },
  globalData: {
    checkLogin: false
  }
  
  ...
})
 

//index.js
//獲取應用實例
const app = getApp()
 
Page({
  data: {
    test: false
  },
  onLoad: function () {
    let that = this;
    //判斷onLaunch是否執行完畢
    if (app.globalData.checkLogin){
      that.setData({
        test:true
      })
    }else{
      app.checkLoginReadyCallback = res => {
      	  //登陸成功后自己希望執行的,和上面一樣
        that.setData({
          test:true
        })
      };
    }
  }
})

方法2:
把 app.js 中的 onLaunch 中登陸后才執行的方法拿到 index.js 文件中,這是最簡單的方法

//index.js

onLoad: function () { 
	wx.login({
	  success: res => {
	    resolve(res); 
	  }
	})
}

方法3:

// app.js中定義一個新的方法
App({
  onLaunch: function () {
  	...
  },
  getAuthKey: function (argument) {
    var that = this;
    return new Promise(function(resolve, reject){
        wx.login({
          success: res => {
            resolve(res); 
          }
        })
    })
  }
  ...
  
})

//index.js
onLoad: function () {
    ...
        
    app.getAuthKey().then(function(res){
      console.log('res')
    })
 }

參考資料:
參考1
參考2
參考3


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM