@nevware21/ts-async
Version:
support for asynchronous development with a Promise based task Scheduler, several different Promise implementations (synchronous, idle, asynchronous and native runtime wrappers), await helpers, and aliases all built and tested using TypeScript.
884 lines (847 loc) • 108 kB
TypeScript
/**
* Calls the provided `callbackFn` function once for each element in an array (or ArratLike) instance in ascending index order. It is not invoked
* for index properties that have been deleted or are uninitialized. And unlike the ES6 forEach() this supports async functions and you CAN stop
* or break the iteration by returning -1 from the `callbackFn` function.
*
* The range (number of elements) processed by arrForEach() is set before the first call to the `callbackFn`. Any elements added beyond the range
* or elements which as assigned to indexes already processed will not be visited by the `callbackFn`.
*
* The `callbackFn` may execute `synchronously` or `asynchronously` and if the `callbackFn` returns a `Promise` then the next iteration will not be
* called until the promise is resolved. If the `callbackFn` returns a `Promise` that is rejected then the iteration will stop and the promise
* returned by arrForEachAsync will be rejected with the same error.
* @since 0.5.0
* @group Loop
* @group Array
* @group ArrayLike
* @typeParam T - Identifies the element type of the array
* @param theArray - The array or array like object of elements to be searched.
* @param callbackFn - A `asynchronous` or `synchronous` function that accepts up to three arguments. arrForEach calls the callbackfn function one
* time for each element in the array.
* @param thisArg - An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, null or undefined
* the array will be used as the this value.
* @remarks
* arrForEachAsync supports either a `synchronous` or `asynchronous` (returns a `Promise`) callback function. If the callback function returns
* a `Promise` then the next iteration will not be called until the promise is resolved. If the callback function returns a `Promise` that is
* rejected then the iteration will stop and the promise returned by arrForEachAsync will be rejected with the same error.
* @example
* ```ts
* const items = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'];
* const copyItems = [];
*
* arrForEachASync(items, (value, index) => {
* copyItems.push(value);
* if (index === 5) {
* return -1; // Stop the iteration
* }
* });
* console.log(copyItems); // ['item1', 'item2', 'item3', 'item4', item5']
*
* // Also supports input as an array like object
* const items = { length: 3, 0: 'item1', 1: 'item2', 2: 'item3' };
*
* // Asynchronous examples using await
* const items = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'];
* const copyItems = [];
*
* await arrForEachASync(items, (value, index) => { // Note: DO NOT use async here unless you use await within the function
* if (index < 5) {
* // Logs each iteration index
* // Logs each value
* console.log(value);
* // Returning a promise will cause `arrForEachAsync` to return a promise to the caller
* // and wait for the promise to resolve before calling the callback function again.
* return createTimeoutPromise(10, true);
* }
*
* return -1; // Stop the iteration
* });
* console.log(copyItems); // ['item1', 'item2', 'item3', 'item4', item5']
*
* ```
*/
export declare function arrForEachAsync<T = any>(theArray: ArrayLike<T>, callbackFn: (value: T, index: number, array: T[]) => void | number | IPromise<void | number>, thisArg?: any): void | number | IPromise<void | number>;
/**
* A Simple type which identifies the result of a promise as a single response, it identifies
* if the promise was rejected or resolved along with the resolved value or rejected reason.
* It is a union of the `IPromiseFulfilledResult` and `IPromiseRejectedResult` interfaces the
* response will contain the `rejected` property which will be true if the promise was rejected
* or false if the promise was resolved. The `status` property will be set to either "fulfilled"
* or "rejected" to identify the status of the promise. The `value` or `reason` properties will
* contain the resolved value or rejected reason respectively.
*
* @group Promise
* @typeParam T - The type of the fulfilled value.
*
* @example
* ```ts
* const result: AwaitResponse<number> = {
* status: "fulfilled",
* value: 42
* };
*
* const result: AwaitResponse<number> = {
* rejected: true,
* status: "rejected",
* reason: "Hello Darkness"
* };
* ```
*/
export declare interface AwaitResponse<T, R = any> {
/**
* A string indicating that the promise was rejected.
*/
status: "fulfilled" | "rejected";
/**
* The value that the promise was fulfilled with.
*/
value?: T;
/**
* The reason that the promise was rejected with.
*/
reason?: R;
/**
* Identifies if the promise was rejected (true) or was resolved (false/undefined)
*/
rejected?: boolean;
}
/**
* Returns a single asynchronous Promise instance that resolves to an array of the results from the input promises.
* This returned promise will resolve and execute it's pending chained operations __asynchronously__ using the optional
* provided timeout value to schedule when the chained items will be executed, or if the input contains no promises.
* It rejects immediately upon any of the input promises rejected or non-promises throwing an error,
* and will reject with this first rejection message / error.
* If the runtime doesn't support the Promise.all it will fallback back to an asynchronous Promise implementation.
*
* @function
* @group Alias
* @group Promise
* @group All
* @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
* @returns
* <ul>
* <li> An already resolved `Promise`, if the input passed is empty.
* <li> A pending `Promise` in all other cases. This returned promise is then resolved/rejected __synchronously__
* (as soon as the pending items is empty) when all the promises in the given input have resolved, or if any of the
* promises reject.
* </ul>
*/
export declare const createAllPromise: <T>(input: Iterable<PromiseLike<T>>, timeout?: number) => IPromise<T[]>;
/**
* Returns a single Promise instance that resolves to an array of the results from the input promises.
* This returned promise will resolve and execute it's pending chained operations based on the current
* promise implementation. If the current implementation is synchronous then the chained operations will
* execute __synchronously__ in the same execution cycle as the final operation pending promises have resolved,
* or if the input contains no promises. If the current implementation is asynchronous then the chained
* operations will execute __asynchronously__ using the optional provided timeout value to schedule when the
* chained items will be executed or if the input contains no promises.
* It will resolve only after all of the input promises have either resolved or rejected, and will resolve with an array
* of {@link IPromiseResult } objects that each describe the outcome of each promise.
* @since 0.5.0
* @group Alias
* @group Promise
* @group AllSettled
* @param values - The iterator of promises to wait to be resolved / rejected before resolving or rejecting the new promise
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A pending `Promise` that will resolve to an array of {@link IPromiseResult } objects that each describe the outcome of each promise.
*
* @example
* ```ts
* const promises = [
* createResolvedPromise(1),
* createResolvedPromise(2),
* createResolvedPromise(3),
* createRejectedPromise("error"),
* ];
*
* const results = await createAllSettledPromise(promises);
*
* // results is:
* // [
* // { status: "fulfilled", value: 1 },
* // { status: "fulfilled", value: 2 },
* // { status: "fulfilled", value: 3 },
* // { status: "rejected", reason: "error" }
* // ]
* ```
*/
export declare function createAllSettledPromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<IPromiseResult<Awaited<T>>[]>;
/**
* The `createAnyPromise` method takes an iterable of promises as input and returns a single Promise.
* This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value.
* It rejects when all of the input's promises reject (including when an empty iterable is passed), with an
* AggregateError containing an array of rejection reasons.
* @since 0.5.0
* @group Alias
* @group Promise
* @group Any
* @param values - An iterable object of promises.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A new Promise that is:
* - Already rejected, if the iterable passed is empty.
* - Asynchronously fulfilled, when any of the promises in the given iterable fulfills. The fulfillment value
* is the fulfillment value of the first promise that was fulfilled.
* - Asynchronously rejected, when all of the promises in the given iterable reject. The rejection reason is
* an AggregateError containing an array of rejection reasons in its errors property. The errors are in the
* order of the promises passed, regardless of completion order. If the iterable passed is non-empty but
* contains no pending promises, the returned promise is still asynchronously (instead of synchronously)
* rejected.
*/
export declare function createAnyPromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<Awaited<T>>;
/**
* Returns a single asynchronous Promise instance that resolves to an array of the results from the input promises.
* This returned promise will resolve and execute it's pending chained operations __asynchronously__ using the optional
* provided timeout value to schedule when the chained items will be executed, or if the input contains no promises.
* It rejects immediately upon any of the input promises rejected or non-promises throwing an error,
* and will reject with this first rejection message / error.
* When resolved or rejected any additional chained operations will execute __asynchronously__ using the optional
* timeout value to schedul when the chained item will be executed (eg. `then()`; `catch()`; `finally()`).
*
* @function
* @group Async
* @group Promise
* @group All
* @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
* @returns
* <ul>
* <li> An already resolved `Promise`, if the input passed is empty.
* <li> A pending `Promise` in all other cases. This returned promise is then resolved/rejected __synchronously__
* (as soon as the pending items is empty) when all the promises in the given input have resolved, or if any of the
* promises reject.
* </ul>
*/
export declare const createAsyncAllPromise: <T>(input: Iterable<PromiseLike<T>>, timeout?: number) => IPromise<T[]>;
/**
* Returns a single Promise instance that resolves to an array of the results from the input promises.
* This returned promise will resolve and execute it's pending chained operations based on the
* {@link createAsyncPromise | Asynchronous} promise implementation. Any chained operations will execute
* __asynchronously__ when the final operation pending promises have resolved, or if the input contains
* no promises. It will resolve only after all of the input promises have either resolved or rejected,
* and will resolve with an array of {@link IPromiseResult } objects that each describe the outcome of
* each promise.
* @since 0.5.0
* @group Async
* @group Promise
* @group AllSettled
* @param values - The iterator of promises to wait to be resolved / rejected before resolving or rejecting the new promise
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A pending `Promise` that will resolve to an array of {@link IPromiseResult } objects that each describe the outcome of each promise.
*
* @example
* ```ts
* const promises = [
* createResolvedPromise(1),
* createResolvedPromise(2),
* createResolvedPromise(3),
* createRejectedPromise("error"),
* ];
*
* const results = await createAllSettledPromise(promises);
*
* // results is:
* // [
* // { status: "fulfilled", value: 1 },
* // { status: "fulfilled", value: 2 },
* // { status: "fulfilled", value: 3 },
* // { status: "rejected", reason: "error" }
* // ]
* ```
*/
export declare function createAsyncAllSettledPromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<IPromiseResult<Awaited<T>>[]>;
/**
* The `createAsyncAnyPromise` method takes an iterable of promises as input and returns a single Promise.
* This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value.
* It rejects when all of the input's promises reject (including when an empty iterable is passed), with an
* AggregateError containing an array of rejection reasons.
* @since 0.5.0
* @group Async
* @group Promise
* @group Any
* @param values - An iterable object of promises.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A new Promise that is:
* - Already rejected, if the iterable passed is empty.
* - Asynchronously fulfilled, when any of the promises in the given iterable fulfills. The fulfillment value
* is the fulfillment value of the first promise that was fulfilled.
* - Asynchronously rejected, when all of the promises in the given iterable reject. The rejection reason is
* an AggregateError containing an array of rejection reasons in its errors property. The errors are in the
* order of the promises passed, regardless of completion order. If the iterable passed is non-empty but
* contains no pending promises, the returned promise is still asynchronously (instead of synchronously)
* rejected.
*/
export declare function createAsyncAnyPromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<Awaited<T>>;
/**
* Creates an asynchronous Promise instance that when resolved or rejected will execute it's pending chained operations
* __asynchronously__ using the optional provided timeout value to schedule when the chained items will be ececuted.
* @group Async
* @group Promise
* @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will
* cause the promise to be rejected. The return value of the executor is always ignored
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
*/
export declare function createAsyncPromise<T>(executor: PromiseExecutor<T>, timeout?: number): IPromise<T>;
/**
* The `createAsyncRacePromise` method takes an array of promises as input and returns a single Promise. This returned promise
* settles with the eventual state of the first promise that settles.
* @description The `createAsyncRacePromise` method is one of the promise concurrency methods. It's useful when you want the first
* async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).
* If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to
* the first of these values found in the iterable.
* @since 0.5.0
* @group Async
* @group Promise
* @group Race
* @param values - An iterable object of promises.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A Promise that settles with the eventual state of the first promise in the iterable to settle. In other words, it fulfills if the
* first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever
* if the iterable passed is empty. If the iterable passed is non-empty but contains no pending promises, the returned promise is still
* asynchronously settled.
*/
export declare function createAsyncRacePromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<Awaited<T>>;
/**
* Returns a single asynchronous Promise instance that is already rejected with the given reason.
* Any chained operations will execute __asynchronously__ using the optional timeout value to schedule
* when then chained items will be executed. (eg. `catch()`; `finally()`).
*
* @function
* @group Async
* @group Promise
* @group Rejected
* @param reason - The rejection reason
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
*/
export declare const createAsyncRejectedPromise: <T = unknown>(reason: any, timeout?: number) => IPromise<T>;
/**
* Returns a single asynchronous Promise instance that is already resolved with the given value. If the value passed is
* a promise then that promise is returned instead of creating a new asynchronous promise instance.
* If a new instance is returned then any chained operations will execute __asynchronously__ using the optional
* timeout value to schedule when the chained items will be executed.(eg. `then()`; `finally()`).
*
* @function
* @group Async
* @group Promise
* @group Resolved
* @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
*/
export declare const createAsyncResolvedPromise: <T>(value: T, timeout?: number) => IPromise<T>;
/**
* Returns an idle Promise instance that resolves to an array of the results from the input promises.
* This returned promise will resolve and execute it's pending chained operations __asynchronously__
* using the `requestIdleCallback` API (if available) with the optional provided timeout value to
* schedule when the chained items will be executed.
* It rejects immediately upon any of the input promises rejected or non-promises throwing an error,
* and will reject with this first rejection message / error.
* When resolved or rejected any additional chained operations will execute __asynchronously__ using
* the `requestIdleCallback` API (if available) with the optional provided timeout value to schedule
* when the chained items will be executed. (eg. `then()`; `catch()`; `finally()`).
*
* @function
* @group Idle
* @group Promise
* @group All
* @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise
* @param timeout - Optional deadline timeout to wait before processing the items, defaults to undefined. If the number of
* milliseconds represented by this parameter has elapsed and the callback has not already been called, then a task to execute
* the callback is queued in the event loop (even if doing so risks causing a negative performance impact). timeout must be a
* positive value or it is ignored.
* @returns
* <ul>
* <li> An already resolved `Promise`, if the input passed is empty.
* <li> A pending `Promise` in all other cases. This returned promise is then resolved/rejected __synchronously__
* (as soon as the pending items is empty) when all the promises in the given input have resolved, or if any of the
* promises reject.
* </ul>
*/
export declare const createIdleAllPromise: <T>(input: Iterable<PromiseLike<T>>, timeout?: number) => IPromise<T[]>;
/**
* Returns a single Promise instance that resolves to an array of the results from the input promises.
* This returned promise will resolve and execute it's pending chained operations based on the
* {@link createIdlePromise | idle} promise implementation. Any chained operations will execute
* __asynchronously__ when the environment is idle as the final operation pending promises have resolved,
* or if the input contains no promises. It will resolve only after all of the input promises have either
* resolved or rejected, and will resolve with an array of {@link IPromiseResult } objects that each describe
* the outcome of each promise.
* @since 0.5.0
* @group Idle
* @group Promise
* @group AllSettled
* @param values - The iterator of promises to wait to be resolved / rejected before resolving or rejecting the new promise
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A pending `Promise` that will resolve to an array of {@link IPromiseResult } objects that each describe the outcome of each promise.
*
* @example
* ```ts
* const promises = [
* createResolvedPromise(1),
* createResolvedPromise(2),
* createResolvedPromise(3),
* createRejectedPromise("error"),
* ];
*
* const results = await createAllSettledPromise(promises);
*
* // results is:
* // [
* // { status: "fulfilled", value: 1 },
* // { status: "fulfilled", value: 2 },
* // { status: "fulfilled", value: 3 },
* // { status: "rejected", reason: "error" }
* // ]
* ```
*/
export declare function createIdleAllSettledPromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<IPromiseResult<Awaited<T>>[]>;
/**
* The `createIdleAnyPromise` method takes an iterable of promises as input and returns a single Promise.
* This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value.
* It rejects when all of the input's promises reject (including when an empty iterable is passed), with an
* AggregateError containing an array of rejection reasons.
* @since 0.5.0
* @group Idle
* @group Promise
* @group Any
* @param values - An iterable object of promises.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A new Promise that is:
* - Already rejected, if the iterable passed is empty.
* - Asynchronously fulfilled, when any of the promises in the given iterable fulfills. The fulfillment value
* is the fulfillment value of the first promise that was fulfilled.
* - Asynchronously rejected, when all of the promises in the given iterable reject. The rejection reason is
* an AggregateError containing an array of rejection reasons in its errors property. The errors are in the
* order of the promises passed, regardless of completion order. If the iterable passed is non-empty but
* contains no pending promises, the returned promise is still asynchronously (instead of synchronously)
* rejected.
*/
export declare function createIdleAnyPromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<Awaited<T>>;
/**
* Creates an idle Promise instance that when resolved or rejected will execute it's pending chained operations
* __asynchronously__ using the `requestIdleCallback` API (if available) with the optional provided timeout value to
* schedule when the chained items will be executed. When `requestIdleCallback` is not available this becomes the same as
* `createAsyncPromise` which uses `setTimeout` to schedule executions.
* @group Idle
* @group Promise
* @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will
* cause the promise to be rejected. The return value of the executor is always ignored
* @param timeout - Optional deadline timeout to wait before processing the items, defaults to undefined. If the number of
* milliseconds represented by this parameter has elapsed and the callback has not already been called, then a task to execute
* the callback is queued in the event loop (even if doing so risks causing a negative performance impact). timeout must be a
* positive value or it is ignored.
*/
export declare function createIdlePromise<T>(executor: PromiseExecutor<T>, timeout?: number): IPromise<T>;
/**
* The `createIdleRacePromise` method takes an array of promises as input and returns a single Promise. This returned promise
* settles with the eventual state of the first promise that settles.
* @description The `createIdleRacePromise` method is one of the promise concurrency methods. It's useful when you want the first
* async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).
* If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to
* the first of these values found in the iterable.
* @since 0.5.0
* @group Idle
* @group Promise
* @group Race
* @param values - An iterable object of promises.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A Promise that settles with the eventual state of the first promise in the iterable to settle. In other words, it fulfills if the
* first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever
* if the iterable passed is empty. If the iterable passed is non-empty but contains no pending promises, the returned promise will settle
* asynchronously when the system detects that the runtime is idle.
*/
export declare function createIdleRacePromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<Awaited<T>>;
/**
* Returns an idle Promise instance that is already rejected with the given reason.
* Any chained operations will execute __asynchronously__ using the o`requestIdleCallback` API
* (if available) with the optional provided timeout value to schedule when the chained items will
* be executed. (eg. `catch()`; `finally()`).
*
* @function
* @group Idle
* @group Promise
* @group Rejected
* @param reason - The rejection reason
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
*/
export declare const createIdleRejectedPromise: <T = unknown>(reason: any, timeout?: number) => IPromise<T>;
/**
* Returns an idle Promise instance that is already resolved with the given value. If the value passed is
* a promise then that promise is returned instead of creating a new asynchronous promise instance.
* If a new instance is returned then any chained operations will execute __asynchronously__ using the
* `requestIdleCallback` API (if available) with the optional provided timeout value to schedule when
* the chained items will be executed. (eg. `then()`; `finally()`).
*
* @function
* @group Idle
* @group Promise
* @group Resolved
* @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
*/
export declare const createIdleResolvedPromise: <T>(value: T, timeout?: number) => IPromise<T>;
/**
* Returns a single asynchronous Promise instance that resolves to an array of the results from the input promises.
* This returned promise will resolve and execute it's pending chained operations __asynchronously__ using the optional
* provided timeout value to schedule when the chained items will be executed, or if the input contains no promises.
* It rejects immediately upon any of the input promises rejected or non-promises throwing an error,
* and will reject with this first rejection message / error.
* If the runtime doesn't support the Promise.all it will fallback back to an asynchronous Promise implementation.
* @group Alias
* @group Promise
* @group All
* @group Native
* @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
* @returns
* <ul>
* <li> An already resolved `Promise`, if the input passed is empty.
* <li> A pending `Promise` in all other cases. This returned promise is then resolved/rejected __synchronously__
* (as soon as the pending items is empty) when all the promises in the given input have resolved, or if any of the
* promises reject.
* </ul>
*/
export declare function createNativeAllPromise<T>(input: Iterable<PromiseLike<T>>, timeout?: number): IPromise<T[]>;
/**
* Returns a single asynchronous Promise instance that resolves to an array of the results from the input promises.
* This returned promise will resolve and execute it's pending chained operations using {@link createNativePromise | native}
* environment promise implementation, if the runtime does not provide any native then the optional provided
* timeout value will be used to schedule when the chained items will be executed or if the input contains no promises.
* It will resolve only after all of the input promises have either resolved or rejected, and will resolve with an array
* of {@link IPromiseResult } objects that each describe the outcome of each promise.
* @since 0.5.0
* @group Alias
* @group Promise
* @group AllSettled
* @group Native
* @param values - The iterator of promises to wait to be resolved / rejected before resolving or rejecting the new promise
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A pending `Promise` that will resolve to an array of {@link IPromiseResult } objects that each describe the outcome of each promise.
*
* @example
* ```ts
* const promises = [
* createNativeResolvedPromise(1),
* createNativeResolvedPromise(2),
* createNativeResolvedPromise(3),
* createNativeRejectedPromise("error"),
* ];
*
* const results = await createNativeAllSettledPromise(promises);
*
* // results is:
* // [
* // { status: "fulfilled", value: 1 },
* // { status: "fulfilled", value: 2 },
* // { status: "fulfilled", value: 3 },
* // { status: "rejected", reason: "error" }
* // ]
* ```
*/
export declare function createNativeAllSettledPromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<IPromiseResult<Awaited<T>>[]>;
/**
* The `createNativeAnyPromise` method takes an iterable of promises as input and returns a single Promise.
* This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value.
* It rejects when all of the input's promises reject (including when an empty iterable is passed), with an
* AggregateError containing an array of rejection reasons.
* @since 0.5.0
* @group Alias
* @group Promise
* @group Any
* @group Native
* @param values - An iterable object of promises.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A new Promise that is:
* - Already rejected, if the iterable passed is empty.
* - Asynchronously fulfilled, when any of the promises in the given iterable fulfills. The fulfillment value
* is the fulfillment value of the first promise that was fulfilled.
* - Asynchronously rejected, when all of the promises in the given iterable reject. The rejection reason is
* an AggregateError containing an array of rejection reasons in its errors property. The errors are in the
* order of the promises passed, regardless of completion order. If the iterable passed is non-empty but
* contains no pending promises, the returned promise is still asynchronously (instead of synchronously)
* rejected.
*/
export declare function createNativeAnyPromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<Awaited<T>>;
/**
* Creates a Promise instance that when resolved or rejected will execute it's pending chained operations using the
* available native Promise implementation.
* If runtime does not support native `Promise` class (or no polyfill is available) this function will fallback to using
* `createAsyncPromise` which will resolve them __asynchronously__ using the optional provided timeout value to
* schedule when the chained items will be executed.
* @group Alias
* @group Promise
* @group Native
* @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will
* cause the promise to be rejected. The return value of the executor is always ignored
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
*/
export declare function createNativePromise<T>(executor: PromiseExecutor<T>, timeout?: number): IPromise<T>;
/**
* The `createNativeRacePromise` method takes an array of promises as input and returns a single Promise. This returned promise
* settles with the eventual state of the first promise that settles.
* @description The `createNativeRacePromise` method is one of the promise concurrency methods. It's useful when you want the first
* async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).
* If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to
* the first of these values found in the iterable.
* @since 0.5.0
* @group Alias
* @group Promise
* @group Race
* @group Native
* @param values - An iterable object of promises.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A Promise that settles with the eventual state of the first promise in the iterable to settle. In other words, it fulfills if the
* first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever
* if the iterable passed is empty. If the iterable passed is non-empty but contains no pending promises, the returned promise will settle
* asynchronously.
*/
export declare function createNativeRacePromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<Awaited<T>>;
/**
* Returns a single asynchronous Promise instance that is already rejected with the given reason.
* Any chained operations will execute __asynchronously__ using the optional timeout value to schedule
* when then chained items will be executed. (eg. `catch()`; `finally()`).
*
* @function
* @group Alias
* @group Promise
* @group Rejected
* @group Native
* @param reason - The rejection reason
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
*/
export declare const createNativeRejectedPromise: <T = unknown>(reason: any, timeout?: number) => Promise<T>;
/**
* Returns a single asynchronous Promise instance that is already resolved with the given value. If the value passed is
* a promise then that promise is returned instead of creating a new asynchronous promise instance.
* If a new instance is returned then any chained operations will execute __asynchronously__ using the optional
* timeout value to schedule when the chained items will be executed.(eg. `then()`; `finally()`).
*
* @function
* @group Alias
* @group Promise
* @group Resolved
* @group Native
* @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
*/
export declare const createNativeResolvedPromise: <T>(value: T, timeout?: number) => Promise<T>;
/**
* Creates a Promise instance using the current default promise creator that when resolved or rejected will execute
* it's pending chained operations.
* @group Alias
* @group Promise
* @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will
* cause the promise to be rejected. The return value of the executor is always ignored
* @param timeout - [Optional] timeout to wait before processing the items, defaults to zero.
*/
export declare function createPromise<T>(executor: PromiseExecutor<T>, timeout?: number): IPromise<T>;
/**
* The `createRacePromise` method takes an array of promises as input and returns a single Promise. This returned promise
* settles with the eventual state of the first promise that settles.
* @description The `createRacePromise` method is one of the promise concurrency methods. It's useful when you want the first
* async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).
* If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to
* the first of these values found in the iterable.
* @since 0.5.0
* @group Alias
* @group Promise
* @group Race
* @param values - An iterable object of promises.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A Promise that settles with the eventual state of the first promise in the iterable to settle. In other words, it fulfills if the
* first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever
* if the iterable passed is empty. If the iterable passed is non-empty but contains no pending promises, the returned promise will settle
* based on the current promise implementation.
*/
export declare function createRacePromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<Awaited<T>>;
/**
* Returns a single asynchronous Promise instance that is already rejected with the given reason.
* Any chained operations will execute __asynchronously__ using the optional timeout value to schedule
* when then chained items will be executed. (eg. `catch()`; `finally()`).
*
* @function
* @group Alias
* @group Promise
* @group Rejected
* @param reason - The rejection reason
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
*/
export declare const createRejectedPromise: <T = unknown>(reason: any, timeout?: number) => IPromise<T>;
/**
* Returns a single asynchronous Promise instance that is already resolved with the given value. If the value passed is
* a promise then that promise is returned instead of creating a new asynchronous promise instance.
* If a new instance is returned then any chained operations will execute __asynchronously__ using the optional
* timeout value to schedule when the chained items will be executed.(eg. `then()`; `finally()`).
*
* @function
* @group Alias
* @group Promise
* @group Resolved
* @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero.
*/
export declare const createResolvedPromise: <T>(value: T, timeout?: number) => IPromise<T>;
/**
* Returns a single synchronous Promise instance that resolves to an array of the results from the input promises.
* This returned promise will resolve and execute it's pending chained operations __synchronously__ in the same
* execution cycle as the final operation pending promises have resolved, or if the input contains no promises.
* It rejects immediately upon any of the input promises rejected or non-promises throwing an error,
* and will reject with this first rejection message / error.
* When resolved or rejected any additional chained operations will execute __synchronously__ at the point of
* being added (eg. `then()`; `catch()`; `finally()`).
*
* @function
* @group Synchronous
* @group Promise
* @group All
* @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise
* @returns
* <ul>
* <li> An already resolved `Promise`, if the input passed is empty.
* <li> A pending `Promise` in all other cases. This returned promise is then resolved/rejected __synchronously__
* (as soon as the pending items is empty) when all the promises in the given input have resolved, or if any of the
* promises reject.
* </ul>
*/
export declare const createSyncAllPromise: <T>(input: Iterable<PromiseLike<T>>) => IPromise<T[]>;
/**
* Returns a single Promise instance that resolves to an array of the results from the input promises.
* This returned promise will resolve and execute it's pending chained operations based on the
* {@link createSyncPromise | synchronous} promise implementation. Any chained operations will execute
* __synchronously__ in the same execution cycle as the final operation pending promises have resolved,
* or if the input contains no promises. It will resolve only after all of the input promises have either
* resolved or rejected, and will resolve with an array of {@link IPromiseResult } objects that each describe
* the outcome of each promise.
* @since 0.5.0
* @group Synchronous
* @group Promise
* @group AllSettled
* @param values - The iterator of promises to wait to be resolved / rejected before resolving or rejecting the new promise
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A pending `Promise` that will resolve to an array of {@link IPromiseResult } objects that each describe the outcome of each promise.
*
* @example
* ```ts
* const promises = [
* createResolvedPromise(1),
* createResolvedPromise(2),
* createResolvedPromise(3),
* createRejectedPromise("error"),
* ];
*
* const results = await createAllSettledPromise(promises);
*
* // results is:
* // [
* // { status: "fulfilled", value: 1 },
* // { status: "fulfilled", value: 2 },
* // { status: "fulfilled", value: 3 },
* // { status: "rejected", reason: "error" }
* // ]
* ```
*/
export declare function createSyncAllSettledPromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<IPromiseResult<Awaited<T>>[]>;
/**
* The `createSyncAnyPromise` method takes an iterable of promises as input and returns a single Promise.
* This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value.
* It rejects when all of the input's promises reject (including when an empty iterable is passed), with an
* AggregateError containing an array of rejection reasons.
* @since 0.5.0
* @group Synchronous
* @group Promise
* @group Any
* @param values - An iterable object of promises.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A new Promise that is:
* - Already rejected, if the iterable passed is empty.
* - Asynchronously fulfilled, when any of the promises in the given iterable fulfills. The fulfillment value
* is the fulfillment value of the first promise that was fulfilled.
* - Asynchronously rejected, when all of the promises in the given iterable reject. The rejection reason is
* an AggregateError containing an array of rejection reasons in its errors property. The errors are in the
* order of the promises passed, regardless of completion order. If the iterable passed is non-empty but
* contains no pending promises, the returned promise is still asynchronously (instead of synchronously)
* rejected.
*/
export declare function createSyncAnyPromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<Awaited<T>>;
/**
* Creates a synchronous Promise instance that when resolved or rejected will execute it's pending chained operations
* __synchronously__ in the same execution cycle as the operation that calls the `executors`, `resolve` or `reject` functions.
*
* @group Synchronous
* @group Promise
* @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will
* cause the promise to be rejected. The return value of the executor is always ignored
*/
export declare function createSyncPromise<T>(executor: PromiseExecutor<T>): IPromise<T>;
/**
* The `createSyncRacePromise` method takes an array of promises as input and returns a single Promise. This returned promise
* settles with the eventual state of the first promise that settles.
* @description The `createSyncRacePromise` method is one of the promise concurrency methods. It's useful when you want the first
* async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).
* If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to
* the first of these values found in the iterable.
* @since 0.5.0
* @group Synchronous
* @group Promise
* @group Race
* @param values - An iterable object of promises.
* @param timeout - Optional timeout to wait before processing the items, defaults to zero, only used when Native promises are not available.
* @returns A Promise that settles with the eventual state of the first promise in the iterable to settle. In other words, it fulfills if the
* first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever
* if the iterable passed is empty. If the iterable passed is non-empty but contains no pending promises, the returned promise will settle
* synchronously.
*/
export declare function createSyncRacePromise<T>(values: Iterable<T | PromiseLike<T>>, timeout?: number): IPromise<Awaited<T>>;
/**
* Returns a single synchronous Promise instance that is already rejected with the given reason.
* Any chained operations will execute __synchronously__ at the point of being added (eg. `catch()`; `finally()`).
*
* @function
* @group Synchronous
* @group Promise
* @group Rejected
* @param reason - The rejection reason
*/
export declare const createSyncRejectedPromise: <T = unknown>(reason: any) => IPromise<T>;
/**
* Returns a single synchronous Promise instance that is already resolved with the given value. If the value passed is
* a promise then that promise is returned instead of creating a new synchronous promise instance.
* If a new instance is returned then any chained operations will execute __synchronously__ at the point of being
* added (calling `then()`).
*
* @function
* @group Synchronous
* @group Promise
* @group Resolved
* @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.
*/
export declare const createSyncResolvedPromise: <T>(value: T) => IPromise<T>;
/**
* Create a Task Scheduler using the optional promise implementation and scheduler name.
* The newPromise can be any value promise creation function, where the execution of the
* queued tasks will be processed based on how the promise implementation processes it's
* chained promises (asynchrounsly; synchronously; idle processing, etc)
*
* The functions used to start each task my return a result (synchronous execution) or an
* {@link IPromise}, `PromiseLike` or `Promise` result (asynchronous execution).
*
* Each task is executed in the order that it was queued and the provided `startTask` function
* will not be called until all previous tasks have completed (whther they resolve or reject).
* The result from any previous task does not affect and is not passed to any later scheduled
* task, if you need this capability then your `startTask` functions will need to co-operate to
* share any common context.
*
* By default, queued tasks which have either been "waiting" to run or have been running longer
* then 10 minutes will be Auto-Rejected to try and free up resources. If a task is running when
* it rejected then it will continue to "run" based on whatever operation it's `startTask` is
* performing. If a task has not yet had it's `startTask` function called it will never get called.
* In both cases the `IPromise` returned by the call to {@link ITaskScheduler.queue | queue} the
* task will be `rejected`. You can change this default time, including disabling completly via
* the {@link ITaskScheduler.setStaleTimeout | setStaleTimeout}
* function.
* @since 0.2.0
* @group Scheduler
* @param newPromise - The function to use for creating a new promise when required, if not
* provided this will default to {@link createPromise} which will use the default registered
* promise creation function which defaults to runtime native promises or async Promise if not
* supported by the runtime.
* @param name - The name you want to associated with this scheduler, mostly useful for debugging
* @re