码迷,mamicode.com
首页 > 微信 > 详细

小程序中解决onLunch()函数的异步

时间:2018-10-25 11:06:50      阅读:410      评论:0      收藏:0      [点我收藏+]

标签:一个   app.js   htm   .com   ESS   ide   lob   bsp   ISE   

问题场景,在我index.js里面需要用到onLunch函数中得到的值,但是在小程序进入启动,已进入index.js时,获取的值不会等到onlunch函数中执行完在拿,所以这时候的index.js所需要的那个值是一个空的。

解决思想:通过promise的方法来解决异步。

使用:在app.js的onlunch函数中:

  getAuthKey: function () {
    console.log("method")
     var that = this;
     return new Promise((resolve,reject)=>{
       //调用登录接口
       wx.login({
         success: function (res) {
           var code = res.code// 登录凭证
           console.log(code, "code码")
           that.globalData.code = code

           wx.getUserInfo({
             success: function (res2) {
               // that.globalData.userInfo = res.userInfo
               typeof cb == "function" && cb(that.globalData.userInfo)
               that.globalData.userInfo = res2.userInfo
               // that.globalData.userInfo2 = res2.userInfo.avatarUrl
               console.log("用户信息", res2)
               wx.request({
                 url: getApp().globalData.url + ‘ywxlogincontroller/login‘,
                 header: {
                   ‘content-type‘: ‘application/x-www-form-urlencoded‘
                 },
                 method: "POST",
                 data: {
                   code: getApp().globalData.code,
                   key: "keyA965C612A7366F79B847AF301E65C5C6",
                 },
                 success: res => {             
                   wx.hideLoading()
                   console.log(getApp().globalData.code, "后台数据", res.data)
                   getApp().globalData.userData = res.data.data;
                   getApp().globalData.userId = res.data.data.user.id;
                   if (res.data.data) {
                     wx.switchTab({
                       url: ‘../index/index‘,
                       success: () => {
                         wx.showToast({
                           title: ‘登录成功‘,
                         })
                         console.log("登录成功", getApp().globalData.userData)
                       },
                     })
                   } else {
                     wx.showToast({
                       title: ‘登录失败‘,
                       icon: "none"
                     })
                   }
                   resolve(res);
                 }
               })
             },
             fail: function () {
               reject(‘error‘);
             }
           })
         }
       })
     })
  }

在index.js中:

const app = getApp()
 app.getAuthKey().then(res=>{
   // 这里就可以在onlunch函数执行完后,在这里等待拿到所需要的值。
})

这里也可以使用 async/await es7新特性 配合着promise使用同样可以达到上面的效果。async/await使用方式可以借鉴我的博客 https://www.cnblogs.com/xuhuang/p/9806255.html

小程序中解决onLunch()函数的异步

标签:一个   app.js   htm   .com   ESS   ide   lob   bsp   ISE   

原文地址:https://www.cnblogs.com/xuhuang/p/9847767.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!