我正在尝试执行两个非并发请求,但想在执行第二个请求之前使用第一个请求中的数据。如何从第一个请求获取数据然后将该数据用于第二个请求?
axios.get('/user/12345').then(response => this.arrayOne = response.data);
axios.get('/user/12345/' + this.arrayOne.name + '/permissions').then(response => this.arrayTwo = response.data);
答案 0 :(得分:5)
您可以将第二个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
);
});
答案 1 :(得分:0)
您还可以在 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));
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);
}
}