axios.post.then 在其他一切之后被调用触发

axios.post.then is called triggered after everything else

我正在尝试创建一个项目,人们可以在其中创建问题和答案。我正在使用 laravel 和 Vuex。

在调用 axios.post 创建问题后,我想用 response.data 创建一个名为 Question_id 的变量。然后我想用这个 Question_id 调用一个函数。

我现在注意到我不能这样做,因为当我尝试在 axios.post 的 .then 部分设置 question_id 变量时,它发生在我调用另一个函数之后。换句话说,.then 部分发生在我所有其他代码具有 运行 之后。

qaForm(){
  axios
    .post("/api/question/create", this.questionForm)
    .then(response => {
      question = response.data;
      question_id = question.id;
    })
    .catch(error => {
      console.log(error.response);
    });

  addQuestion(question_id);
}

我可以确认我的 consoling.out 不同步骤。如果我运行这个实验:

qaForm(){
  console.log("before axios post"); // runs 1st

  axios
    .post("/api/question/create", this.questionForm)
    .then(response => {
      console.log("inside axios.then"); // runs 3rd

      question = response.data;
      question_id = question.id;
    })
    .catch(error => {
      console.log(error.response);
    });

  console.log("after axios post"); // runs 2nd
  addQuestion(question_id);
}

我收到:

before axios post
after axios post
inside axios.then

为什么会这样?我犯了什么错误吗?有哪些可能的解决方法?

我看过你以前的代码,一切正常,因为是一个 axios 请愿书。例如,您可以在您的商店中尝试这样的事情。

async actionStore(){
    const response = await axios.post('/api/question/create', this.questionForm;
    if(isok){
     //commit to store
     return something;
    } else return some error;  
}

然后在组件内的方法中试试这个。

qaForm()
        {

            actionStore().then((response)=>{
                if(response isok)
                 addQuestion(question_id);
             });


        }

这只是一个例子,因为我现在看不到你所有的代码 请记住,store return 承诺的操作。

Axios 请求是异步的,因此 return 是一个承诺。这就是为什么 then() 中的代码在下面的代码之后执行的原因。

简单的解决方法是将代码移到响应处理程序中

qaForm(){
  console.log("before axios post"); // runs 1st

  axios
    .post("/api/question/create", this.questionForm)
    .then(response => {
      console.log("inside axios.then"); // runs 2nd

      question = response.data;
      question_id = question.id;

      console.log("after axios post"); // runs 3rd
      addQuestion(question_id);
    })
    .catch(error => {
      console.log(error.response);
    });
}

当你第一次看到它时可能会觉得有点奇怪,这是我处理异步函数的首选方式。

然而,JavaScript 语言引入了 async-await 功能,允许您以一种您可能会发现更直观的方式重写代码。

注意代码中asyncawait的使用。

async q0aForm() {
  console.log("before axios post"); // 1st

  let response = await axios.post("/api/question/create", this.questionForm)
  console.log("no more axios.then"); // 2nd

  question = response.data;
  question_id = question.id;

  console.log("after axios post"); // 3rd
  addQuestion(question_id);
}