Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Manage Multiple Requests with Promise.all

why is the variables breedList and randomImage's index start at [0] and [1], aren't both supposed to be [0]?

const breedList = data[0].message;

const randomImage = data[1].message;

When accessing the arrays for the breed list and url using promise.all() and the fetch API?

1 Answer

He explains that when you use Promise.all(), it combines the responses from both fetch requests into one single promise. He logs the response of Promise.all() into the console so we can see what is actually returned. We see that it returns an array of two objects: the first object is the response from the first fetch request. The object has a message property that is an array of the list of dog breeds. The second object is the response from the second fetch request and this object has a message property that is a URL of an image.

//response returns an array of objects
Promise.all([
  //first object's message property is an array of breeds
  fetchData('https://dog.ceo/api/breeds/list'),
  //second object's message property is a URL link
  fetchData('https://dog.ceo/api/breeds/image/random')
])
//print response to console to see how it looks
.then(data => console.log(data))

Open this link in a new tab to see what shows up on the console

He then deletes the console.log() method and manipulates the data appropriately:

//manipulate data from each object returned.
.then(data => {
  //get message from the first object in the response. The message stores an array of breeds
  const breedList = data[0].message;
  //get message from the second object in the response. The message stores a URL
  const randomImage = data[1].message;

  generateOptions(breedList);
  generateImage(randomImage);
})