title: Resolve promise when all images are loaded
body: <p>I was preloading images with the following code:</p>
  
  <pre><code>    function preLoad() {
          var deferred = $q.defer();
          var imageArray = [];
          for (var i = 0; i &lt; $scope.abbreviations.length; i++) {
              imageArray[i] = new Image();
              imageArray[i].src = $scope.abbreviations[i].imgPath;
          }
          imageArray.forEach.onload = function () {
              deferred.resolve();
              console.log('Resolved');
          }
          imageArray.forEach.onerror = function () {
              deferred.reject();
              console.log('Rejected')
          }
          return deferred.promise;
      }
      preLoad();
  </code></pre>
  
  <p>I thought images were all loading correctly because I could see the 'Resolved' log.</p>
  
  <p>Later somebody pointed out that the code above doesn't guarantee that all images are loaded before resolving the promise. In fact, only the first promise is resolved.</p>
  
  <p>I was advised to use <code>$q.all</code> applied to an array of promises instead.
  This is the resulting code:</p>
  
  <pre><code>    function preLoad() {
          var imageArray = [];
          var promises;
          for (var i = 0; i &lt; $scope.abbreviations.length; i++) {
              imageArray[i] = new Image();
              imageArray[i].src = $scope.abbreviations[i].imgPath;
          };
  
          function resolvePromises(n) {
              return $q.when(n);
          }
          promises = imageArray.map(resolvePromises);
          $q.all(promises).then(function (results) {
              console.log('array promises resolved with', results);
          });
      }
      preLoad();
  </code></pre>
  
  <p>This works, but I want to understand:</p>
  
  <ol>
  <li>what's happening in each function;</li>
  <li>why I need <code>$q.all</code> to make sure all images are loaded before resolving the promises.</li>
  </ol>
  
  <p>The <a href="https://docs.angularjs.org/api/ng/service/$q" rel="nofollow">relevant docs</a> are somewhat cryptic.</p>