Middle+
Why should you rely on a count variable in the implementation of promiseAll instead of simply checking the length of the results array?
sobes.tech AI
Answer from AI
In the implementation of Promise.all, you can't just check the length of the results array because promises can resolve in any order, and some may resolve with an error before others.
The count variable is only incremented when a promise successfully resolves, which allows us to accurately track how many promises have already completed. If we only checked the length of the results array, we might mistakenly think that all promises have finished, even if some are still pending or if an error has occurred.
Example:
function promiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let count = 0;
promises.forEach((p, i) => {
Promise.resolve(p)
.then(value => {
results[i] = value;
count++;
if (count === promises.length) {
resolve(results);
}
})
.catch(err => reject(err));
});
});
}
Here, count guarantees that we wait for all promises to settle, not just for the presence of elements in the results array.