Applet asynchronous sign-on solution

wx.login()

Get openid above applet code must be acquired through the front wx.login () method, passing back through the front over the code to the micro channel request to obtain key information openid, session_key of the like, the rear end may be performed by a user login service development code,

wx.login () asynchronous request

In the usual logon development, usually the package log on to app.js in onLaunch in (login development approach is not unique), the user will be open every time the user logs on cold, we will conduct some business after logging development and data request, if the execution order after the event, app.js in the onLaunch method applet is triggered at initialization, onLoad method should be performed only under the Pages document, but wx.login () Gets the time code request is asynchronous data request , so when the request wx.login () method has not yet ended, onLoad under Pages file has been executed, the consequences of this induction is the first data request, onLoad Pages under the following execution speed file app.js been greater than in the onLaunch execution speed.

Interim Solution

Now that we know the order is executed because the results of an asynchronous request, it can be processed by Promise method ES6 provided, heard the callback function to request another page.
code
Directory to the root directory of -app.js

  userLogin:function(){
    let that = this;
    let promise = new Promise((resolve, reject)=>{
      wx.login({
        success: function (res) {
          wx.request({
            url: '服务器地址',
            dataType: "json",
            data: '要传递的参数code',
            method: method,
            header: {'Content-Type': 'application/x-www-form-urlencoded'},
            success: function (res) {
              resolve(res);
            },
          })
        },
        fail(error) {
          reject(error)
        }
      })
    })
    return promise;
  },

pages>index.js>onLoad

const app = getApp()
app.userLogin().then((res)=>{
    //数据请求成功之后的操作
    //可以请求其他的数据了
},(error)=>{
    console.log('数据请求失败:'+error)
})

Guess you like

Origin blog.csdn.net/WANG_CA/article/details/83658737