【问题标题】:Performing multiple requests Axios (Vue.js)执行多个请求 Axios (Vue.js)
【发布时间】:2017-06-06 21:06:17
【问题描述】:

我正在尝试执行两个非并发请求,但想在执行第二个请求之前使用我第一个请求中的数据。如何从第一个请求中获取数据,然后将该数据用于第二个请求?

axios.get('/user/12345').then(response => this.arrayOne = response.data);
axios.get('/user/12345/' + this.arrayOne.name + '/permissions').then(response => this.arrayTwo = response.data);

【问题讨论】:

    标签: http vuejs2 vue.js axios


    【解决方案1】:

    您可以将第二个 axios 调用嵌套在第一个调用中。

    axios.get('/user/12345').then(response => {
       this.arrayOne = response.data
       axios.get('/user/12345/' + this.arrayOne.name + '/permissions').then(
           response => this.arrayTwo = response.data
         );
      });
    

    【讨论】:

      【解决方案2】:

      您也可以在 ES2017 中使用 async/await

      myFunction = async () => {
        const response1 = await axios.get('/user/12345');
        this.arrayOne = response1.data;
        const response2 = await axios.get(`/user/12345/${this.arrayOne.name}/permissions`);
        this.arrayTwo = response2.data;
      }
      myFunction().catch(e => console.log(e));
      

      myFunction = async () => {
        try {
          const response1 = await axios.get('/user/12345');
          this.arrayOne = response1.data;
          const response2 = await axios.get(`/user/12345/${this.arrayOne.name}/permissions`);
          this.arrayTwo = response2.data;
        } catch(e) {
          console.log(e);
        }
      }
      

      【讨论】:

      • 谢谢,这比选择的答案更能帮助我
      猜你喜欢
      • 2019-03-07
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2017-11-03
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多