I am trying to write my Promise.all() function.
It should repeat the functionality of the native Promise.all() method.
If there are only promises in the array, the code works correctly, probably the problem appears if the array contains something other than a promise.
Here is an example of execution:
const p1 = Promise.resolve(3);
const p2 = 1337;
const p3 = new Promise((resolve, reject) => {
setTimeout(resolve, 10000, 'foo');
});
promiseAll([p1, p3, p3]).then(values => console.log(values)); // [3, 1337, "foo"]
Here is my code:
const promiseAll = promises => new Promise((resolve, reject) => {
if (promises.length === 0) { resolve([]); }
const results = [];
let resolved = 0;
promises.forEach(promise => {
if (!(promise instanceof Promise)) {
Promise.resolve(promise).then(data => results.push(data));
}
promise.then(result => {
results.push(result);
resolved += 1;
if (resolved === promises.length) {
resolve(results);
}
}, error => reject(error));
});
});
What is the problem?