我试图在Vue.js中的另一个函数之后执行一个函数。我已经尝试过async / await,回调函数,.then,但是它不知何故不想一个接一个地加载。有什么可能的解决方案?
auth_mixin.js:
async auth () {
console.log("authban")
var token = this.getCookie("token")
var jsonData = {}
jsonData["token"] = token
console.log(jsonData)
var bodyFormData = new FormData();
bodyFormData.append('data', JSON.stringify(jsonData));
axios({
method: 'post',
url: 'backend/index.php?action=checkAuth',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function (response) {
console.log(response);
if(response.data.status==="OK"){
console.log("ok")
return true;
}else{
console.log("nem ok")
return false;
}
})
.catch(function (response) {
console.log(response);
return false;
});
}
Navbar.vue:
created () {
var result=false
this.auth().then(this.checkIfLoggedIn(result))
},
methods: {
checkIfLoggedIn (isLoggedIn) {
console.log("na ez lesz az erdekes "+isLoggedIn)
if(isLoggedIn === true){
console.log("true")
document.getElementById("logged_out").style.display="none";
document.getElementById("logged_in").style.display="block";
}else{
console.log("fail");
}
}
}
this.auth().then(this.checkIfLoggedIn(result))
您有两个问题。
首先:this.checkIfLoggedIn(result)
调用checkIfLoggedIn
立即。您需要将一个函数传递给then
。
this.auth().then(() => this.checkIfLoggedIn(result))
第二:进行此更改后,当checkIfLoggedIn
解析时,您将调用auth
。
[auth
何时解析?好吧,它是用async
关键字定义的,因此它可以在returns
时解析(除非它返回一个promise,在这种情况下,它将采用那个promise)。
那么它返回什么?它没有return
语句,因此它到达结尾时会返回undefined
…这是在axios
调用之后(因为您没有await
调用)。
如果您return
使用了axios(...).etc
的返回值,那么直到that
((此外:您正在使用async
,您应该重构为使用await
,try {} catch() {}
而不是.then()
和.catch()
)]