首页 > 解决方案 > 我想在完成后执行 axios 请求

问题描述

我有 axios 请求获取一些数据并将其存储在本地存储中我想在第一个请求完成后发出另一个请求并使用第一个请求响应数据

this.$http.post("http://localhost:8000/oauth/token", data).then(response => { 
      this.$auth.setToken(
        response.data.access_token,
        response.data.expires_in + Date.now()
      );
    }).then(()=>{
      this.$http.get("user").then(response => {
        this.$auth.setAuthenticatedUser(response.data);
        this.user = response.data;
        this.image = response.data.image;
        this.$bus.$emit('logged_user',response.data);
      });

      this.$http
        .get("http://localhost:8000/api/tpa/provider/status")
        .then(res => {
          localStorage.setItem("tpa_provider", JSON.stringify(res.data));
      });

      this.$bus.$emit('logged_user',this.user);

      if(this.$auth.isAuth()){
        this.$router.push({"name":"home"});
      }

我也尝试使用异步等待,但我无法实现

标签: javascriptvue.jsecmascript-6axioses6-promise

解决方案


选项 1。您可以将结果传递给下一个,然后通过return.

this.$http.post("http://localhost:8000/oauth/token", data).then(response => {
  // ...
  return response;
}).then((myResponse) => {
  console.log('first result', myResponse);
  // ...
});

选项 2。您可以将第一个请求的结果存储在 superscope 变量中。

let myResponse;

this.$http.post("http://localhost:8000/oauth/token", data).then(response => {
  myResponse = response;
  // ...
}).then(() => {
  console.log('first result', myResponse);
  // ...
});

推荐阅读