title: Waiting for all elements to fully with Promise.all
body: <p>I've been trying to figure out how Promises work with a rather simple example: one that fetches a number of images, loads it onto the page in order, counts the number of images loaded.</p>
  
  <pre><code>const addImg = url =&gt; {
      fetch(url)
          .then(validateResponse)
          .then(readResponseAsBlob)
          .then(showImage)
          .catch(Error);
  }
  
  function showImage(responseAsBlob) {
      const container = document.getElementById('img-container');
      const imgElem = document.createElement('img');
      container.appendChild(imgElem);
      const imgUrl = URL.createObjectURL(responseAsBlob);
      imgElem.src = imgUrl;
      return imgUrl;
  }
  
  document.getElementById("add").onclick = () =&gt; {
      document.getElementById("status").innerHTML = "Fetching...";
      Promise.all(urls.map(url =&gt; addImg(url)))
          .then(setTimeout(() =&gt; {
              document.getElementById("status").innerHTML = document.getElementsByTagName("img").length + " images";
          }, 0));
  }
  </code></pre>
  
  <p>The addImg function fetches an image from the url, processes it as a blob and <code>showImage</code> renders adds a new img. When I try to add images from an array of urls, I have noticed a few problems I want to fix:</p>
  
  <ol>
  <li>The images don't necessarily show up in order</li>
  <li>the img count is not accurate</li>
  </ol>
  
  <p>My first thought: if I deconstruct the addImg function so that it execute each step as a separate promise( fetch all -> then validate all -> then ... so on), it might work the way I intend it to, but I'm not sure if that's the right approach to it.</p>