stevekane / promise-it-wont-hurt

A Workshopper module that teaches you to use promises in javascript
737 stars 219 forks source link

Exercise 11, solution that takes any number of promises as an array, like Promise.all() #141

Open AlexandroPerez opened 6 years ago

AlexandroPerez commented 6 years ago

So I came up with the following solution after a lot of mistakes, and a solution that didn't run in parallel, like do promise2 only after promise1 is done.

I think it runs in parallel, since I did a console.log(i) inside the for loop, and the number of promises passed to function all() printed instantly... but I can't say I'm sure it really works in parallel.

'use strict';

function all(promisesArray) {
  return new Promise(function(fulfill, reject) {
    let size = promisesArray.length;
    let counter = 0;
    let values = [];

    for (let i = 0; i < size; i++){
      promisesArray[i].then(function(value) {
        values[i] = value;
        counter++;
        if (counter === size) fulfill(values);
      });
    }
  });
}

all([getPromise1(), getPromise2()]).then(console.log);