Learn the concept
Promises & Async/Await
Promise.all takes an iterable of promises and returns a single promise that resolves with an array of all results (preserving order) or rejects with the first rejection. Promise.race returns a promise that settles with the first promise to settle, whether fulfilled or rejected.
Implementing Promise combinators from scratch is a common interview question at companies like Swiggy, where Promise.race polyfill has been confirmed in online assessments. These implementations test understanding of Promise internals, iteration, and concurrent resolution patterns.
Behavior:
[]Key Implementation Details:
results.length since array indices can be set out of order)Promise.resolve(item) to wrap non-promise valuesBehavior:
Promise.resolve(), making them settle synchronously via microtaskBehavior:
{ status: 'fulfilled', value } or { status: 'rejected', reason } objectsBehavior:
AggregateErrorfunction promiseAll(iterable) {
return new Promise((resolve, reject) => {
const items = Array.from(iterable);
if (items.length === 0) {
resolve([]);
return;
}
const results = new Array(items.length);
let resolvedCount = 0;
items.forEach((item, index) => {
Promise.resolve(item).then(
(value) => {
results[index] = value; // Preserve order
resolvedCount++;
if (resolvedCount === items.length) {
resolve(results);
}
},
(reason) => {
reject(reason); // Fail fast on first rejection
}
);
});
});
}
// Tests
promiseAll([1, Promise.resolve(2), 3]).then(console.log);
// [1, 2, 3]
promiseAll([
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments'),
]).then(([users, posts, comments]) => {
console.log('All loaded');
});
// Fail fast
promiseAll([
Promise.resolve('ok'),
Promise.reject('fail'),
new Promise(() => {}), // Never settles
]).catch(console.log); // 'fail' — rejects immediatelyUsing Promise.race to implement fetch timeouts by racing the actual request against a timer promise, ensuring requests don't hang indefinitely.
Using Promise.all to fetch multiple API endpoints concurrently and wait for all results before rendering a dashboard or page.
Build a function that runs promises with a maximum concurrency limit (e.g., process 100 URLs but only 5 at a time), combining all four combinator patterns.