【问题标题】:i want to execute axios request after one is finished我想在完成后执行 axios 请求
【发布时间】:2019-01-19 01:57:23
【问题描述】:

我有 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"});
      }

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

【问题讨论】:

  • 你总是可以在第二个中使用多个.then().then().then(),例如,你可以使用res = response,该响应将有助于第一个数据的值
  • 你的意思是 {response.then(res => {})}
  • 这不起作用我不希望它们连续我希望它们在第一次执行之后阻止第二次执行
  • 这条评论和你对问题的描述有很大不同。也许试着更好地澄清你的问题

标签: javascript vue.js ecmascript-6 axios es6-promise


【解决方案1】:

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

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

选项 2。您可以将第一个请求的结果存储在超级作用域变量中。

let myResponse;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-18
    • 2018-10-13
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2017-12-12
    相关资源
    最近更新 更多