解决微信小程序app.js中异步请求尚未执行完成,就执行Page页面请求的问题

JavaScript07

解决微信小程序app.js中异步请求尚未执行完成,就执行Page页面请求的问题,第1张

问题描述:在app.js中执行login请求获取token,home.js中的请求会出现不带token的情况。 原因:app.js中的login请求是异步操作,所以会出现执行home.js中请求的时候,login请求还未执行完成,因此获取不到token。 解决方法:在app.js中使用Promise;在home.js判断Promise的状态,已完成时再去执行页面的请求。

//app.js

App({

  onLaunch: function () {

    let App = this

    // 设置api地址

    App.setApiRoot()

  },

  globalData: {

    userInfo: null

  },

  api_root: '', // api地址

  appid:'',

  /**

   * 显示失败提示框

   */

  showError(msg, callback) {

    wx.showModal({

      title: '友情提示',

      content: msg,

      showCancel: false,

      success(res) {

        callback && callback()

      }

    })

  },

   /**

   * 设置api地址

   */

  setApiRoot() {

    let App = this

    // App.api_root = config.config.host

    let extConfig = wx.getExtConfigSync? wx.getExtConfigSync(): {}

    console.log(extConfig)

    App.appid = extConfig.attr.appid

    App.api_root = extConfig.attr.host

  },

  /**

   * get请求

   */

  _get(url, data, success, fail, complete, check_login) {

    let App = this

    wx.showNavigationBarLoading()

    // 构造请求参数

    data = Object.assign({

      token: wx.getStorageSync('token'),

      appid:App.appid  

    }, data)

    // if (typeof check_login === 'undefined')

    //   check_login = true

    console.log(App.api_root) 

    // 构造get请求

    let request = () => {

      data.token = wx.getStorageSync('token')

      wx.request({

        url: App.api_root + url,

        header: {

          'content-type': 'application/json'

        },

        data,

        success(res) { 

          if (res.statusCode !== 200 || typeof res.data !== 'object') {

            console.log(res)

            App.showError('网络请求出错') 

            return false

          } 

          if (res.data.code === -1) {

            // 登录态失效, 重新登录

            wx.hideNavigationBarLoading()

            App.doLogin(() => {

              App._get(url, data, success, fail)

            })

          } else if (res.data.code === 0) {

            App.showError(res.data.msg)

            return false

          } else {

            success && success(res.data)

          }

        },

        fail(res) {

          // console.log(res)

          App.showError(res.errMsg, () => {

            fail && fail(res)

          })

        },

        complete(res) {

          wx.hideNavigationBarLoading()

          complete && complete(res)

        },

      })

    }

    // 判断是否需要验证登录

    check_login ? App.doLogin(request) : request()

  },

  /**

   * post提交

   */

  _post_form(url, data, success, fail, complete) {

    wx.showNavigationBarLoading()

    let App = this

    // 构造请求参数 

    data = Object.assign({

      token: wx.getStorageSync('token'), 

      appid:App.appid  

    }, data)

    data.token = wx.getStorageSync('token')

    wx.request({

      url: App.api_root + url,

      header: {

        'content-type': 'application/x-www-form-urlencoded',

      },

      method: 'POST',

      data,

      success(res) {

        if (res.statusCode !== 200 || typeof res.data !== 'object') {

          App.showError('网络请求出错')

          return false

        }

        if (res.data.code === -1) {

          // 登录态失效, 重新登录

          App.doLogin(() => {

            App._post_form(url, data, success, fail)

          })

          return false

        } else if (res.data.code === 0) {

          App.showError(res.data.msg, () => {

            fail && fail(res)

          })

          return false

        }

        success && success(res.data)

      },

      fail(res) {

        // console.log(res)

        App.showError(res.errMsg, () => {

          fail && fail(res)

        })

      },

      complete(res) {

        wx.hideLoading()

        wx.hideNavigationBarLoading()

        complete && complete(res)

      }

    })

  },

   /**

   * 验证登录

   */

  checkIsLogin() {

    return wx.getStorageSync('token') != ''

  }, 

  /**

   * 授权登录

   */

  doLogin(callback) { 

    let App = this

    // if (e.detail.errMsg !== 'getUserInfo:ok') {

    //   return false

    // }

    wx.showLoading({

      title: "加载数据中...",

      mask: true

    }) 

    // 执行微信登录

    wx.login({ 

      success(res) {

        // 发送用户信息 

        App._post_form('login', {

          code: res.code,

        }, result => {

          // 记录token user_id

          wx.setStorageSync('token', result.data.token,)

          // 执行回调函数

          callback && callback()

        }, false, () => {  

          wx.hideLoading()

        })

      }

    }) 

  }

})