【问题标题】:My asynchronous javascript gets executed in the middle of the other function我的异步 javascript 在另一个函数的中间执行
【发布时间】:2020-03-23 22:10:20
【问题描述】:

我试图在 Vue.js 中的另一个函数之后执行一个函数。我已经尝试过异步/等待、回调函数、.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");
      }
    }
  }

【问题讨论】:

  • 第一个明显的问题...问题,.then 需要一个函数作为参数,其他任何东西都被忽略(在这种情况下立即执行)-另一个问题,为什么使用 var result = false 并通过 @987654327 @ 到 this.checkIfLoggedIn 而不仅仅是 this.checkIfLoggedIn(false) - 因为这是你的代码唯一能通过的东西

标签: javascript vue.js asynchronous promise callback


【解决方案1】:
this.auth().then(this.checkIfLoggedIn(result))

你有两个问题。

首先:this.checkIfLoggedIn(result)立即致电checkIfLoggedIn。您需要将一个函数传递给then。

this.auth().then(() => this.checkIfLoggedIn(result))

第二:有了这个改变,当auth 解决时,你调用checkIfLoggedIn。

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

那么它返回了什么?它没有return 语句,所以它在结束时返回undefined……这是在调用axios 之后立即返回的(因为你不是awaiting)。

如果您returned 了axios(...).etc 的返回值,那么直到 承诺解决后它才会解决。

(除此之外:您正在使用async,您可能应该重构为使用await、try {} catch() {} 而不是.then() 和.catch())。

【讨论】:

  • 非常感谢,我现在完全明白了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多