Kontext
Promise.all and arrays of Promises
In the previous exercise we saw how we can perform multiple requests. Although we did it, we used async / await before every response. That means that every time we made a request to the API, we paused further execution of our function until the response came back. That means that the order of execution was:
Request nr.1 made
Response nr.1 received
Do something with Response nr.1
Request nr.2 made
Response nr.2 received
Do something with Response nr.2
etc.
Although we don't block any code outside the async function, we do it for the code inside the function. What if we want to change the order, to make all requests, at the same time, without waiting for responses? Like texting 5 times a message to 5 different friends, and then wait for them to answer. Maybe no-one answers, maybe all of them do at the same time, but for the in between time, the only thing we have is 5 promises. Now normally, if we want to save a new Promise object in order to return it later, we must save it into a single variable. But now if we make multiple fetches inside a loop, we can't. Instead we can use an array and push there every new promise for every fetch request we make. In the end we end up with an array of promises! Nice!
But now we have another problem! normally we know that when a function returns a single promise, we can define what is going to happen after, by chaining a .then() function. But now we have an array of promises and we need to define that we want to execute further, only when all promises have been fulfilled (when all responses are back). So the execution order will be something like this:
Request nr.1 made, Save the promise nr1. into an array
Request nr.2 made, Save the promise nr.2 into the array
Request nr.3 made, Save the promise nr.3 into the array
Request nr.4 made, Save the promise nr.4 into the array
Wait for all responses to come in any order. Then after we have gathered all the
data objects into this array, we execute normally. We can now loop and create HTML elements for every data object that we have etc as before.
We use the Promise.all([promise1, promise2, promise3, promise4]) in order to express that
the next .then() function (or the next line after the await) is going to be executed only AFTER all promises have been fulfilled and all responses are back.
Bear in mind! The data that is going to be passed in the next .then() function (or is going to be stored in the await variable depending on the method you prefer) is going to be an Array of values! In this case an array of object, that contains the data and all the responses.
As shown in line 18, 'allImages' variable is now an array, and if we want to show all of them we must create a loop, to create a corresponding HTML element every time, for every response we got back.
Documentation of the Promise.all function