Reputation: 703
I need to make a bunch of API calls and combine their data finally like this
axios.all([
axios.get('https://api.github.com/users/mapbox'),
axios.get('https://api.github.com/users/phantomjs')
])
.then(responseArr => {
//this will be executed only when all requests are complete
console.log('Date created: ', responseArr[0].data.created_at);
console.log('Date created: ', responseArr[1].data.created_at);
});
But I also want to use the data received in one API in the other API call. Kind of like this
data = axios.get('https://api.github.com/users/mapbox'),
axios.get('https://api.github.com/users/'+data.user);
How do I use this for like 5 API calls?
Upvotes: 0
Views: 3220
Reputation: 1295
I will use async-await for this.
async function fetchData(){
try {
const response = await axios.get("https://api.github.com/users/mapbox");
const res = response.data;
const getUser = await axios.get(`https://api.github.com/users/${res.user}`);
const getWhatever = getUser.data;
......
......
} catch (error) {
console.log(error)
}
}
You could also use a nested .then method whenever you get the results and then use that to make another request. But I think async-await is better.
Upvotes: 2