uni-app中 控制onLaunch和onLoad的異步請求先后順序


小程序一般都需要在app.vue的onLaunch做一個異步請求獲取用戶的openId和token之后才能執行頁面的onLoad里的異步請求,像平常用async await控制異步請求的先后順序,

在小程序里也一樣,只不是需要做成全局的。

如 :在main.js里掛載

Vue.prototype.$getToken = new Promise(resolve => {
  Vue.prototype.$isResolve = resolve;
})

然后在app.vue中

  onLaunch: function () {
     let that=this;
     wx.login({
      success(res) {
        if (res.code) {
          // 發起網絡請求 獲取openId
          that.$http({
            url: "/wouu/applets/getToken",
            method: "post",
            data: {
              code: res.code,
            },
          }).then((res) => {
            console.log("999", res);
            //調用
            that.$isResolve();

          });
        } else {
          console.log("登錄失敗!" + res.errMsg);
        }
      },
    });
  },

在頁面的onLoad()處

async onLoad() {
     // 等待登錄結果返回
    await this.$getToken;
    this.$http({
      url:'/wdse/applets/qddSceewData',
      method:'post',
      data:{
        scene:'rdsmend',//場景值推薦
      }
    }).then(res=>{
      console.log('dssa',res)
    })
   
  },

 


免責聲明!

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



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