Modern Promise polyfills including static utility methods and instance methods for asynchronous programming patterns, error handling, and promise composition.
Core Promise functionality with enhanced static utility methods for advanced asynchronous patterns.
/**
* Promise constructor with enhanced static methods
*/
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all provided promises resolve
* @param values - An iterable of promises
*/
all<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]>;
/**
* Creates a Promise that resolves after all provided promises have settled
* @param values - An iterable of promises
*/
allSettled<T>(values: Iterable<T | PromiseLike<T>>): Promise<PromiseSettledResult<Awaited<T>>[]>;
/**
* Returns a promise that fulfills with the first promise that fulfills
* @param values - An iterable of promises
*/
any<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;
/**
* Returns a promise that settles with the same fate as the first promise that settles
* @param values - An iterable of promises
*/
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;
/**
* Returns a Promise object that is resolved with the given value
* @param value - Value to resolve with
*/
resolve<T>(value: T | PromiseLike<T>): Promise<Awaited<T>>;
resolve(): Promise<void>;
/**
* Returns a Promise object that is rejected with the given reason
* @param reason - Reason for rejection
*/
reject<T = never>(reason?: any): Promise<T>;
/**
* Wraps a function call in a promise, catching synchronous errors
* @param fn - Function to execute
*/
try<T>(fn: () => T | PromiseLike<T>): Promise<T>;
/**
* Returns a promise with its resolve and reject functions exposed
*/
withResolvers<T>(): {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
};
}Usage Examples:
import Promise from 'core-js-pure/stable/promise';
// Promise.allSettled - Wait for all promises to settle
const promises = [
Promise.resolve(1),
Promise.reject(new Error('failed')),
Promise.resolve(3)
];
const results = await Promise.allSettled(promises);
console.log(results);
// [
// { status: 'fulfilled', value: 1 },
// { status: 'rejected', reason: Error('failed') },
// { status: 'fulfilled', value: 3 }
// ]
// Promise.any - First fulfilled promise
const anyResult = await Promise.any([
Promise.reject(new Error('error 1')),
Promise.resolve('success'),
Promise.resolve('also success')
]);
console.log(anyResult); // 'success'
// Promise.try - Safe function execution
const safeResult = await Promise.try(() => {
// Might throw synchronously or return a promise
return JSON.parse('{"valid": "json"}');
});
console.log(safeResult); // { valid: 'json' }
// Promise.withResolvers - External control
const { promise, resolve, reject } = Promise.withResolvers();
setTimeout(() => {
resolve('resolved after delay');
}, 1000);
const result = await promise; // 'resolved after delay'Instance methods available on Promise objects for chaining and error handling.
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise
* @param onfulfilled - Callback for fulfilled state
* @param onrejected - Callback for rejected state
*/
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null
): Promise<TResult1 | TResult2>;
/**
* Attaches a callback for only the rejection of the Promise
* @param onrejected - Callback for rejected state
*/
catch<TResult = never>(
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null
): Promise<T | TResult>;
/**
* Attaches a callback that is invoked when the Promise is settled
* @param onfinally - Callback for settled state
*/
finally(onfinally?: (() => void) | undefined | null): Promise<T>;
}Usage Examples:
import Promise from 'core-js-pure/stable/promise';
// Promise chaining with error handling
const processData = (data) => {
return Promise.resolve(data)
.then(data => {
console.log('Processing:', data);
return data.toUpperCase();
})
.catch(error => {
console.error('Processing failed:', error);
return 'DEFAULT';
})
.finally(() => {
console.log('Processing complete');
});
};
// Advanced error handling patterns
const robustFetch = async (url) => {
return Promise.try(async () => {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
})
.catch(error => {
console.error('Fetch failed:', error);
throw error;
})
.finally(() => {
console.log('Request completed');
});
};Type definitions for Promise settlement results.
/**
* Result type for Promise.allSettled
*/
type PromiseSettledResult<T> = PromiseFulfilledResult<T> | PromiseRejectedResult;
interface PromiseFulfilledResult<T> {
status: 'fulfilled';
value: T;
}
interface PromiseRejectedResult {
status: 'rejected';
reason: any;
}Usage Examples:
import Promise from 'core-js-pure/stable/promise';
// Handling mixed success/failure scenarios
const mixedOperations = [
fetch('/api/data1').then(r => r.json()),
fetch('/api/data2').then(r => r.json()),
fetch('/invalid-url').then(r => r.json())
];
const results = await Promise.allSettled(mixedOperations);
const successes = results
.filter(result => result.status === 'fulfilled')
.map(result => result.value);
const failures = results
.filter(result => result.status === 'rejected')
.map(result => result.reason);
console.log('Successful responses:', successes.length);
console.log('Failed requests:', failures.length);import Promise from 'core-js-pure/stable/promise';
// Process multiple items concurrently with error handling
const processItemsConcurrently = async (items) => {
const operations = items.map(item =>
Promise.try(() => processItem(item))
);
const results = await Promise.allSettled(operations);
return {
successful: results
.filter(r => r.status === 'fulfilled')
.map(r => r.value),
failed: results
.filter(r => r.status === 'rejected')
.map(r => r.reason)
};
};import Promise from 'core-js-pure/stable/promise';
// Add timeout to any operation
const withTimeout = (promise, ms) => {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), ms)
);
return Promise.race([promise, timeout]);
};
// Use with external resolvers for complex control flow
const createCancellableOperation = () => {
const { promise, resolve, reject } = Promise.withResolvers();
const operation = withTimeout(promise, 5000);
return {
promise: operation,
resolve,
reject,
cancel: () => reject(new Error('Cancelled'))
};
};import Promise from 'core-js-pure/stable/promise';
// Process items in batches to control concurrency
const processBatches = async (items, batchSize = 3) => {
const results = [];
for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize);
const batchPromises = batch.map(item =>
Promise.try(() => processItem(item))
);
const batchResults = await Promise.allSettled(batchPromises);
results.push(...batchResults);
}
return results;
};