So I was following along an MDN article on promises and was wondering how to modify the following code to be able to work for any number of files (not just 3).
function fetchAndDecode(url) { return fetch(url).then(response => { if(!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { if(response.headers.get("content-type") === "image/jpeg") { return response.blob(); } else if(response.headers.get("content-type") === "text/plain") { return response.text(); } } }) .catch(e => { console.log(`There has been a problem with your fetch operation for resource "${url}": ` + e.message); }) .finally(() => { console.log(`fetch attempt for "${url}" finished.`); }) } let coffee = fetchAndDecode('coffee.jpg'); let tea = fetchAndDecode('tea.jpg'); let description = fetchAndDecode('description.txt'); Promise.all([coffee, tea, description]).then(values => { console.log(values); // Store each value returned from the promises in separate variables; create object URLs from the blobs let objectURL1 = URL.createObjectURL(values[0]); let objectURL2 = URL.createObjectURL(values[1]); let descText = values[2]; // Display the images in <img> elements let image1 = document.createElement('img'); let image2 = document.createElement('img'); image1.src = objectURL1; image2.src = objectURL2; document.body.appendChild(image1); document.body.appendChild(image2); // Display the text in a paragraph let para = document.createElement('p'); para.textContent = descText; document.body.appendChild(para); }); MDN specifically notes that "If you were improving this code, you might want to loop through a list of items to display, fetching and decoding each one, and then loop through the results inside Promise.all(), running a different function to display each one depending on what the type of code was. This would make it work for any number of items, not just three." I'm not sure how to do this though, and would appreciate help. Thanks.
const fileNames = ['coffee.jpg', 'tea.jpg', 'description.txt'].valuesis already an array, so think about looping through that usingforeach. but you also need to think about file types. that is, you need to find a way to pass in the type of the file along with the file content, since you need to create the appropriate html element based on the type. right now it knows the type for each because it's hard coded.values, images becomeBlobinstances while text files become strings.