Installation
npx fragmen add promise/all-settled-typedSource Code
/**
* Type-safe Promise.allSettled with separated results
* @param promises Array of promises
* @returns Object with fulfilled and rejected arrays
* @example
* const { fulfilled, rejected } = await allSettledTyped([
* Promise.resolve(1),
* Promise.resolve(2),
* Promise.reject(new Error('failed'))
* ]);
* // fulfilled: [1, 2]
* // rejected: [Error('failed')]
*
* const { fulfilled, rejected } = await allSettledTyped([
* fetch('/api/user'),
* fetch('/api/posts'),
* fetch('/api/comments')
* ]);
* console.log(`${fulfilled.length} succeeded, ${rejected.length} failed`);
*/
export async function allSettledTyped<T>(promises: Promise<T>[]): Promise<{
fulfilled: T[];
rejected: Error[];
}> {
const results = await Promise.allSettled(promises);
const fulfilled: T[] = [];
const rejected: Error[] = [];
results.forEach(result => {
if (result.status === 'fulfilled') {
fulfilled.push(result.value);
} else {
rejected.push(result.reason);
}
});
return { fulfilled, rejected };
}
Examples
const { fulfilled, rejected } = await allSettledTyped([
Promise.resolve(1),
Promise.resolve(2),
Promise.reject(new Error('failed'))
]);
// fulfilled: [1, 2]
// rejected: [Error('failed')]
const { fulfilled, rejected } = await allSettledTyped([
fetch('/api/user'),
fetch('/api/posts'),
fetch('/api/comments')
]);
console.log(`${fulfilled.length} succeeded, ${rejected.length} failed`);Related Utilities
delay
promiseReturns a promise that resolves after a given number of milliseconds. Creates an artificial delay using Promise and setTimeout. Useful for implementing timeouts, rate limiting, animation delays, or simulating async operations in testing.
retry
promiseRetries a promise-returning function a specified number of times with exponential backoff. Attempts to execute the function, and if it fails, retries up to the specified number of times. Each retry waits longer than the previous one (exponential backoff). Useful for handling flaky network requests, rate-limited APIs, or temporary failures.
timeout
promiseWraps a promise with a timeout, rejecting if it doesn't resolve within the specified time. Creates a race between the provided promise and a timeout. If the promise doesn't resolve or reject before the timeout, it will be rejected with a timeout error. Useful for preventing indefinite hangs, enforcing SLAs, or handling slow operations gracefully.
Quick Actions
Parameters
promisesanyArray of promises
Returns
unknownObject with fulfilled and rejected arrays