Implementing Promise.all
<p>One of the <a href="http://eloquentjavascript.net/17_http.html#h_MlI+KUOVBK" rel="noreferrer">exercises</a> in  Chapter 17 of the book Eloquent Javascript is to implement the Promise.all() method, I came up with this implementation (which doesn't work):</p>

<pre><code>function all(promises) {
  return new Promise(function(success, fail) {
    var successArr = new Array(promises.length);
    if (promises.length == 0)
      success(successArr);
    var pending = promises.length;
    for (var i = 0; i &lt; promises.length; i++) {
      promises[i].then(function(result) {
        successArr[i] = result;
        pending -= 1;
        if (pending == 0)
          success(successArr);
      }, function(error) {
        fail(error);
      });
    }
  });
}


// Testing
function soon(val) {
  return new Promise(function(success) {
    setTimeout(function() { success(val); },
               Math.random() * 500);
  });
}
all([soon(1), soon(2), soon(3)]).then(function(array) {
  console.log("This should be [1, 2, 3]:", array);
});
// =&gt; [undefined, undefined, undefined, 3]
</code></pre>

<p>Interestingly, the author's solution is similar apart from the use of forEach to iterate over the promises array instead of the for loop in my case:</p>

<pre><code>function all(promises) {
  return new Promise(function(success, fail) {
    var successArr = new Array(promises.length);
    if (promises.length == 0)
      success(successArr);
    var pending = promises.length;
    promises.forEach(function(promise, i) {
      promise.then(function(result) {
        successArr[i] = result;
        pending -= 1;
        if (pending == 0)
          success(successArr);
      }, function(error) {
        fail(error);
      });
    });
  });
}

// Testing
function soon(val) {
  return new Promise(function(success) {
    setTimeout(function() { success(val); },
               Math.random() * 500);
  });
}
all([soon(1), soon(2), soon(3)]).then(function(array) {
  console.log("This should be [1, 2, 3]:", array);
});
// =&gt; [1, 2, 3]
</code></pre>

<p>Why does the use forEach makes all the difference here?, I'm guessing it's something related to the scope created by the anonymous function passed to forEach, but I can't quite figure how that works.</p>