我的异步 javascript 在另一个函数中间执行

My asynchronous javascript gets executed in the middle of the other function

我正在尝试在 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))

其次:随着这个改变,你在 auth 结算时调用 checkIfLoggedIn

那么auth什么时候解决?嗯,它是用 async 关键字定义的,所以它在 returns 时解析(除非它 return 是一个承诺,在这种情况下它会采用那个承诺)。

那是什么 return?它没有 return 语句,所以当它结束时它 returns undefined ......这是在调用 axios 之后立即(因为你不是 await那个)。

如果您 return 编辑了 axios(...).etc 的 return 值,那么在 承诺解决之前它不会解决。

(另外:您正在使用 async,您可能应该重构为使用 awaittry {} catch() {} 而不是 .then().catch())。