我的异步javascript在其他函数的中间执行

问题描述 投票:-1回答:1

我试图在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");
      }
    }
  }

Order of execution

javascript vue.js asynchronous promise callback
1个回答
0
投票
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,您应该重构为使用awaittry {} catch() {}而不是.then().catch())]

© www.soinside.com 2019 - 2024. All rights reserved.