Performing multiple requests Axios (Vue.js)

微笑、不失礼 提交于 2019-12-22 17:48:40

问题


I am trying to perform two, non-concurrent request, but would like to use data from my first request before performing a second request. How can I achieve getting the data from the first request then using that data for the second request?

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

回答1:


You can just nest the second axios call inside the first one.

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:


You could also use async/await in ES2017:

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));

OR

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);
  }
}


来源:https://stackoverflow.com/questions/41787994/performing-multiple-requests-axios-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!