Promise.all
is a method that takes an array of promises and returns a single promise that resolves when all of the promises have resolved.
Promise.all([ Promise.resolve('foo'), Promise.resolve('bar'), Promise.resolve('baz'), ])
Let's take a look at how we can create a naive implementation of Promise.all
.
function promiseAll(promises: Promise<unknown>[]) {
return new Promise((resolve, reject) => {
if (promises.length === 0) {
resolve([])
return
}
const results: unknown[] = new Array(promises.length)
let resolvedCount = 0
promises.forEach((promise, index) => {
promise
.then((result) => {
results[index] = result
resolvedCount++
if (resolvedCount === promises.length) {
resolve(results)
}
})
.catch(reject)
})
})
}
For each promise, we add the result of the promise to the results array at the index of the promise. We then increment the resolved count and check if it matches the length of the input array. If it does, we resolve the returned promise with the results array.
If at any point, a promise rejects, the returned promise will reject with the error that the promise rejected with.
An edge case to consider is when the input array is empty. In this case, we resolve the returned promise with an empty array.