Implement Promise.all
Fan out over the inputs, settle each one independently, and resolve with the results in their original order the moment the last one lands — rejecting eagerly if any fail.
The problem
Reimplement `Promise.all()`. It takes an iterable of values — promises or plain values — and returns a single promise that resolves to an array of the resolved results, in the same order as the input.
The combined promise resolves only once every input has resolved. If any input rejects, the combined promise rejects immediately with that first error, ignoring whatever the rest do.
The approach
I return a new promise and pre-size a `results` array to the input length, filled with `null`, so I can drop each result into its own slot by index. Order matters, and the promises won't settle in order — writing to `results[i]` keeps the output lined up with the input regardless of who finishes first.
I wrap each input in `Promise.resolve()` so plain non-promise values get lifted into promises too, then attach `.then`. A `resolvedPromisesCount` counter tracks how many have landed; when it equals `promises.length` I resolve with `results`. Any rejection calls `rej` directly — and since a promise can only settle once, the first error wins and the later ones are harmless no-ops.
The solution
function promiseAll(promises) {
return new Promise((res, rej) => {
const results = Array(promises.length).fill(null)
let resolvedPromisesCount = 0
for (let i = 0; i < promises.length; i++) {
Promise.resolve(promises[i]).then((data) => {
resolvedPromisesCount++
results[i] = data
if (resolvedPromisesCount === promises.length) {
res(results)
}
}).catch((err) => {
rej(err)
})
}
})
};Time O(n)Space O(n)