0

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?

1
  • Sequence calls by either using await or nesting .then() as shown here. Commented Jul 15, 2020 at 0:04

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.