Promise.all() takes an array of promises and returns a single promise that:
- Resolves when all promises succeed → returns an array of results.
- Rejects immediately if any promise fails → returns the first error.
We can implement a custom version using basic Promise logic.
1️⃣ Custom Implementation
function myPromiseAll(promises) {
return new Promise((resolve, reject) => {
if (!Array.isArray(promises)) {
return reject(new TypeError("Input must be an array"));
}
const results = [];
let completed = 0;
promises.forEach((p, index) => {
// Ensure non-promises are wrapped in Promise.resolve
Promise.resolve(p)
.then((value) => {
results[index] = value;
completed++;
// If all promises are done, resolve with results
if (completed === promises.length) {
resolve(results);
}
})
.catch((err) => {
reject(err); // Reject immediately if any promise fails
});
});
// Handle empty array
if (promises.length === 0) {
resolve([]);
}
});
}
2️⃣ Example Usage
const p1 = Promise.resolve(1);
const p2 = new Promise((res) => setTimeout(() => res(2), 500));
const p3 = Promise.resolve(3);
myPromiseAll([p1, p2, p3])
.then((results) => console.log("Results:", results))
.catch((err) => console.error("Error:", err));
✅ Output after 500ms:
Results: [1, 2, 3]
3️⃣ Key Points
Promise.resolve(p)ensures that even non-promise values are handled.- Results are stored in the original order using the
index. - Rejects immediately if any promise fails, just like native
Promise.all(). - Handles empty arrays by resolving immediately with
[].
In short:
myPromiseAllmimicsPromise.all()by tracking completions, storing results in order, and rejecting immediately if any promise fails.