Promise.all

by sbjami

HTML

<body>
  <h1>Promise.all</h1>
  <button id="fetchBtn">
    Fetch data
  </button>
  <p id="userData1">
    User 1 data goes here
  </p>
  <hr>
  <p id="userData2">
    User 2 data goes here
  </p>
</body>

CSS

button {
  color: red;
}

JavaScript

const baseUrl = "https://jsonplaceholder.typicode.com";
const usersUrl = `${baseUrl}/users`;
const usersArray = [1, 2];

const fetchAsync = async url => {
  const response = await fetch(url);
  const data = await response.json();
  return data;
}

document.getElementById("fetchBtn").addEventListener("click", async () => {
	// Notice how the map operation takes in an async function which always
  // returns promises and usersData will therefore be an array of promises
  const usersData = usersArray.map(async user => fetchAsync(`${usersUrl}/${user}`));
  Promise.all(usersData).then(completed => {
    completed.map((user, index) => {
      document.getElementById(`userData${index + 1}`).innerText = JSON.stringify(user);
    });
  });
})