user2643810
user2643810

Reputation:

How to get the data from an array of urls with axios and promises

I have this endpoint that gives me the info about a specific character, looks like this:

Endpoint: https://rickandmortyapi.com/api/character/1

that gives me back an object with the name of the chracter as well as other properies, one of those properties is called episode.

{
  name: 'Ricky',
  id: 1,
  episode: [...]
}

And the episode property contains an aray of urls that look like this:

[
  "https://rickandmortyapi.com/api/episode/1",
  "https://rickandmortyapi.com/api/episode/2",
  "https://rickandmortyapi.com/api/episode/3"
  ...
]

I know I should use Promise.all and somehow loop over these and then resolve them but I cant get it to work.

This is what I tried, but I dont know if its correct, and it always gives back a promise no matter how many times I do .then

let episodeResponses;

  const episodesResponses = Promise.all(character.episode.map(url => {
    return axios(url)
      .then(resp => episodeResponses = resp)
  }))

  episodesResponses.then(x => console.log(x))

Any ideas on how to get this working?

Thanks

Upvotes: 1

Views: 355

Answers (1)

Gregg
Gregg

Reputation: 667

In a simplified form, this API call will look something like this.

const episodes = [
    axios('https://rickandmortyapi.com/api/episode/1'),
    axios('https://rickandmortyapi.com/api/episode/2'),
    axios('https://rickandmortyapi.com/api/episode/3')
];

Promise.all(episodes).then((data) => {
  const episode1 = data[0];
  const episode2 = data[1];
  const episode3 = data[2];
});

Call .then() on Promise.all instead. Once all promises are resolved, then you will have access to your data.

// Create a promise using Promise.all().
const episodeResponses = Promise.all(character.episode.map(url => axios(url)));

// Access the response once all promises are resolved.
episodesResponses.then(x => console.log(x))

Upvotes: 1

Related Questions