Middle
Live coding: implement a polyfill for the Promise.all method, including preserving the order of results.
sobes.tech AI
Answer from AI
The implementation of a polyfill for Promise.all should accept an array of promises and return a new promise that:
- resolves when all promises in the array resolve,
- rejects if any of the promises reject,
- maintains the order of results according to the order of the input promises.
function promiseAll(promises) {
return new Promise((resolve, reject) => {
if (!Array.isArray(promises)) {
return reject(new TypeError('Argument must be an array'));
}
const results = [];
let completed = 0;
const total = promises.length;
if (total === 0) {
return resolve([]);
}
promises.forEach((p, index) => {
Promise.resolve(p)
.then(value => {
results[index] = value;
completed += 1;
if (completed === total) {
resolve(results);
}
})
.catch(err => {
reject(err);
});
});
});
}
This code handles both promises and regular values (via Promise.resolve), carefully maintains the order of results, and correctly handles errors.