problem description
such as the title. I get the token from the server in app.js, and then bring it to the access interface in the future. However, the onload in index.js is loaded at about the same time as the request in app.js when it is loaded for the first time, so it cannot be accessed properly for the first time. How to make the request in app.js complete and then load the request in index.js. Promise is currently known, but will not be used.
the environmental background of the problems and what methods you have tried
https://www.jianshu.com/p/90f... is exactly the same as this article. I wrote it according to him, but it didn"t work.
related codes
/ / Please paste the code text below (do not replace the code with pictures)
onLaunch: function () {/ / app.js
this.getToken()
},
/ / Log in
getToken: function () {
let this_ = this
return new Promise(function (resolve, reject) {
wx.login({
success: function (res) {
var code = res.code;
if (code) {
let istoken = wx.getStorageSync("token");
if (istoken != "") {
} else { //istoken
wx.request({
url: cIdUrl.cIdUrl + "/wechat/auth/" + code, //
header: {
"Content-Type": "application/json"
},
method: "GET",
data: {
code: code,
},
success: function (res) {
if (res.statusCode == 200) {
let token = res.data.data.token //token
wx.setStorage({key: "token", data: token })
console.log(token)
resolve(token)
} else {
console.log("")
}
},
fail: function (red) {
console.log("app.js")
}
}) //request
}
} else {
console.log(":" + res.errMsg);
}
} //login
}) //login
})
}
here is the home page, and getData () is the method for loading data on the home page
onLoad: function () {
let this_ = this
let token = wx.getStorageSync("token");
if (token == "") {
//
app.getToken().then(function (res) {
this_.getData();
})
} else {
//token
this_.getData();
}
}