Socket
Socket
Sign inDemoInstall

@handy-common-utils/promise-utils

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@handy-common-utils/promise-utils - npm Package Compare versions

Comparing version 1.4.1 to 1.5.0

204

dist/promise-utils.d.ts

@@ -35,4 +35,4 @@ /**

/**
* Do an operation repeatedly and collect all the results.
* This function is useful for client side pagination.
* Executes an operation repeatedly and collects all the results.
* This function is very useful for many scenarios, such like client-side pagination.
*

@@ -47,15 +47,15 @@ * @example

*
* @template Result type of the operation result
* @template Param type of the input to the operation, normally the input is a paging parameter
* @template Collection type of the returned value of this function
* @template Result The type of the operation result.
* @template Param The type of the input to the operation, typically a paging parameter.
* @template Collection The type of the collection returned by this function.
*
* @param operation a function that takes paging parameter as input and outputs a result, normally the operation supports paging
* @param nextParameter The function for calculating next parameter from the operation result.
* Normally the parameter controls paging,
* This function should return null when next invocation of the operation function is not desired.
* If next invocation is desired, the return value of this function can be a Promise or not a Promise.
* @param collect the function for merging operation result into the collection
* @param initialCollection initial collection which would be the first argument passed into the first invocation of the collect function
* @param initialParameter the parameter for the first operation
* @returns Promise of collection of all the results returned by the operation function
* @param operation A function that takes a parameter as input and returns a result. Typically, the parameter has optional fields to control paging.
* @param nextParameter A function for calculating the next parameter from the operation result.
* Normally, this parameter controls paging.
* This function should return null when no further invocation of the operation function is desired.
* If further invocation is desired, the return value of this function can be a Promise or a non-Promise value.
* @param collect A function for merging the operation result into the collection.
* @param initialCollection The initial collection, which will be the first argument passed to the first invocation of the collect function.
* @param initialParameter The parameter for the first operation.
* @returns A promise that resolves to a collection of all the results returned by the operation function.
*

@@ -65,3 +65,3 @@ */

/**
* Do an operation repeatedly until a criteria is met.
* Repeatedly performs an operation until a specified criteria is met.
*

@@ -73,31 +73,56 @@ * @example

*
* @template Result type of the operation result
* @template TError type of the possible error that could be generated by the operation
* @template Result Type of the operation result.
* @template TError Type of the possible error that could be generated by the operation.
*
* @param operation a function that outputs a Promise result, normally the operation does not use its arguments
* @param backoff Array of retry backoff periods (unit: milliseconds) or function for calculating them.
* If retry is desired, before making next call to the operation the desired backoff period would be waited.
* If the array runs out of elements or the function returns `undefined` or either the array or the function returns a negative number,
* there would be no further call to the operation.
* The `attempt` argument passed into backoff function starts from 1 because the function is called right after the first attempt and before the first retry.
* @param shouldRetry Predicate function for deciding whether another call to the operation should happen.
* If this argument is not defined, retry would happen whenever the operation rejects with an error.
* `shouldRetry` would be evaluated before `backoff`.
* The `attempt` argument passed into shouldRetry function starts from 1.
* @returns Promise of the operation result potentially with retries already applied
* @param operation A function that outputs a Promise result. Typically, the operation does not use its arguments.
* @param backoff An array of retry backoff periods (in milliseconds) or a function for calculating them.
* If retry is desired, the specified backoff period is waited before the next call to the operation.
* If the array runs out of elements or the function returns `undefined` or a negative number, no further calls to the operation will be made.
* The `attempt` argument passed to the backoff function starts from 1, as it is called immediately after the first attempt and before the first retry.
* @param shouldRetry A predicate function for deciding whether another call to the operation should occur.
* If this argument is not defined, a retry will occur whenever the operation rejects with an error.
* The `shouldRetry` function is evaluated before the `backoff`.
* The `attempt` argument passed to the shouldRetry function starts from 1.
* @returns A promise of the operation result, potentially with retries applied.
*/
static withRetry<Result, TError = any>(operation: (attempt: number, previousResult: Result | undefined, previousError: TError | undefined) => Promise<Result>, backoff: Array<number> | ((attempt: number, previousResult: Result | undefined, previousError: TError | undefined) => number | undefined), shouldRetry?: (previousError: TError | undefined, previousResult: Result | undefined, attempt: number) => boolean): Promise<Result>;
/**
* Run multiple jobs/operations in parallel.
* Executes multiple jobs/operations with a specified level of concurrency.
*
* By default this function does not throw / reject with error when any of the job/operation fails.
* Operation errors are returned together with operation results in the same returned array.
* That also means this function only returns when all the jobs/operations settle (either resolve or reject).
* Unlike `inParallel(...)`, this function may throw or reject an error when a job/operation fails.
* When an error is re-thrown, remaining operations will not be executed.
* If you want all the operations to always be executed, use {@link PromiseUtils.inParallel} instead.
*
* However, if options.abortOnError is true, this function throws / rejects with error when any of the job/operation fails.
* That also means, some of the jobs/operations may not get the chance to be executed if one of them fails.
* @example
* // At any time, there would be no more than 5 concurrency API calls. Error would be re-thrown immediately when it occurs.
* const attributes = await PromiseUtils.withConcurrency(5, topicArns, async (topicArn) => {
* const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;
* return topicAttributes;
* });
*
*
* @template Data The type of the job data, typically an Array.
* @template Result The type of the return value from the operation function.
*
* @param concurrency The number of jobs/operations to run concurrently.
* @param jobs The job data to be processed. This function can handle an infinite or unknown number of elements safely.
* @param operation The function that processes job data asynchronously.
* @returns A promise that resolves to an array containing the results from the operation function.
* The results in the returned array are in the same order as the corresponding elements in the jobs array.
*/
static withConcurrency<Data, Result>(concurrency: number, jobs: Iterable<Data>, operation: (job: Data, index: number) => Promise<Result>): Promise<Array<Result>>;
/**
* Executes multiple jobs/operations in parallel. By default, all operations are executed regardless of any failures.
* In most cases, using {@link PromiseUtils.withConcurrency} might be more convenient.
*
* By default, this function does not throw or reject an error when any job/operation fails.
* Errors from operations are returned alongside results in the returned array.
* This function only resolves when all jobs/operations are settled (either resolved or rejected).
*
* If `options.abortOnError` is set to true, this function throws (or rejects with) an error immediately when any job/operation fails.
* In this mode, some jobs/operations may not be executed if one fails.
*
* @example
* // Capture errors in the returned array
* const attributesAndPossibleErrors = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
* const attributesAndPossibleErrors: Array<JobResult|JobError> = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
* const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;

@@ -115,13 +140,14 @@ * return topicAttributes;

*
* @template Data Type of the job data, usually it would be an Array
* @template Result Type of the return value of the operation function
* @template Data The type of the job data, typically an Array.
* @template Result The type of the return value from the operation function.
* @template TError The type for the error that could be thrown from the operation function, defaults to `Result`.
*
* @param parallelism how many jobs/operations can be running at the same time
* @param jobs job data which will be the input to operation function.
* This function is safe when there are infinite unknown number of elements in the job data.
* @param operation the function that turns job data into result asynchronously
* @param options Options for controlling the behavior of this function.
* @returns Promise of void if the operation function does not return a value,
* or promise of an array containing outcomes from the operation function.
* In the returned array containing outcomes, each element is either the fulfilled result, or the rejected error/reason.
* @param parallelism The number of jobs/operations to run concurrently.
* @param jobs The job data to be processed. This function can safely handle an infinite or unknown number of elements.
* @param operation The function that processes job data asynchronously.
* @param options Options to control the function's behavior.
* @param options.abortOnError If true, the function aborts and throws an error on the first failed operation.
* @returns A promise that resolves to an array containing the results of the operations.
* Each element is either a fulfilled result or a rejected error/reason.
* The results or errors in the returned array are in the same order as the corresponding elements in the jobs array.
*/

@@ -132,14 +158,16 @@ static inParallel<Data, Result, TError = Result>(parallelism: number, jobs: Iterable<Data>, operation: (job: Data, index: number) => Promise<Result>, options?: {

/**
* Create a Promise that resolves after number of milliseconds specified
* @param ms number of milliseconds after which the created Promise would resolve
* @param result the result to be resolved for the Promise, or a function that supplies the result.
* @returns the new Promise created
* Creates a Promise that resolves after a specified number of milliseconds.
*
* @param ms The number of milliseconds after which the created Promise will resolve.
* @param result The result to be resolved by the Promise, or a function that supplies the result.
* @returns A new Promise that resolves with the specified result after the specified delay.
*/
static delayedResolve<T>(ms: number, result?: T | PromiseLike<T> | (() => (T | PromiseLike<T>))): Promise<T>;
/**
* Create a Promise that rejects after number of milliseconds specified.
* @param ms number of milliseconds after which the created Promise would reject
* @param reason the reason of the rejection for the Promise, or a function that supplies the reason.
* If the reason ends up to be a rejected Promise, then the outcome (could be fulfilled or rejected) of it will be the reject reason of the Promise returned.
* @returns the new Promise created
* Creates a Promise that rejects after a specified number of milliseconds.
*
* @param ms The number of milliseconds after which the created Promise will reject.
* @param reason The reason for the rejection, or a function that supplies the reason.
* If the reason is a rejected Promise, the outcome of it will be the rejection reason of the returned Promise.
* @returns A new Promise that rejects with the specified reason after the specified delay.
*/

@@ -149,11 +177,12 @@ static delayedReject<T = never, R = any>(ms: number, reason: R | PromiseLike<R> | (() => R | PromiseLike<R>)): Promise<T>;

* Applies a timeout to a Promise or a function that returns a Promise.
* If the timeout occurs, resolves to the specified result.
* If the timeout doesn't occur, the resolved result or rejection reason of the original Promise will be the outcome of the Promise returned from this function.
* If the 'result' parameter is a function and timeout doesn't occur, the function won't be called.
* The rejection of the 'operation' parameter is not handled by this function, you may want to handle it outside of this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously".
* If the timeout occurs, the returned Promise resolves to the specified result.
* If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
* If the `result` parameter is a function and the timeout does not occur, the function will not be called.
* Note: The rejection of the `operation` parameter is not handled by this function.
* You may want to handle it outside this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously."
*
* @param operation The original Promise or a function that returns a Promise for which the timeout will be applied.
* @param operation The original Promise or a function that returns a Promise to which the timeout will be applied.
* @param ms The number of milliseconds for the timeout.
* @param result The result to be resolved with if the timeout occurs, or a function that supplies the result.
* @return A new Promise that resolves to the specified result if the timeout occurs.
* @param result The result to resolve with if the timeout occurs, or a function that supplies the result.
* @returns A new Promise that resolves to the specified result if the timeout occurs.
*/

@@ -163,18 +192,19 @@ static timeoutResolve<T>(operation: Promise<T> | (() => Promise<T>), ms: number, result?: T | PromiseLike<T> | (() => (T | PromiseLike<T>)) | undefined): Promise<T>;

* Applies a timeout to a Promise or a function that returns a Promise.
* If the timeout occurs, rejects with the specified reason.
* If the timeout doesn't occur, the resolved result or rejection reason of the original Promise will be the outcome of the Promise returned from this function.
* If the 'reason' parameter is a function and timeout doesn't occur, the function won't be called.
* The rejection of the 'operation' parameter is not handled by this function, you may want to handle it outside of this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously".
* If the timeout occurs, the returned Promise rejects with the specified reason.
* If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
* If the `rejectReason` parameter is a function and the timeout does not occur, the function will not be called.
* Note: The rejection of the `operation` parameter is not handled by this function. You may want to handle it outside this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously."
*
* @param operation The original Promise or a function that returns a Promise for which the timeout will be applied.
* @param operation The original Promise or a function that returns a Promise to which the timeout will be applied.
* @param ms The number of milliseconds for the timeout.
* @param rejectReason The reason to reject with if the timeout occurs, or a function that supplies the reason.
* @return A new Promise that rejects with the specified reason if the timeout occurs.
* @returns A new Promise that rejects with the specified reason if the timeout occurs.
*/
static timeoutReject<T = never, R = any>(operation: Promise<T> | (() => Promise<T>), ms: number, rejectReason: R | PromiseLike<R> | (() => R | PromiseLike<R>)): Promise<T>;
/**
* Get the state of the Promise.
* Please note that the returned value is a Promise, although it resolves immediately.
* @param p the Promise for which we would like to know its state
* @return A Promise that resolves immediately containing the state of the input Promise
* Retrieves the state of the specified Promise.
* Note: The returned value is a Promise that resolves immediately.
*
* @param p The Promise whose state is to be determined.
* @returns A Promise that resolves immediately with the state of the input Promise.
*/

@@ -184,19 +214,21 @@ static promiseState(p: Promise<any>): Promise<PromiseState>;

/**
* Equivalent of `synchronized` in Java.
* In any situation there's no concurrent execution of any operation function associated with the same lock.
* The operation function has access to the state (when `synchronized` is called), settledState (when the operation function is called),
* and result (could be the fulfilled result or the rejected reason) of the previous operation.
* In case there is no previous invocation, state, settledState and result would all be undefined.
* @param lock the object (could be a string, a number, or `this` in a class) that is used to apply the lock
* @param operation function for doing the computation and returning a Promise
* @returns the result of the operation function
* Provides mutual exclusion similar to `synchronized` in Java.
* Ensures no concurrent execution of any operation function associated with the same lock.
* The operation function has access to the state (when `synchronized` is called),
* settledState (when the operation function is called),
* and result (either the fulfilled result or the rejected reason) of the previous operation.
* If there is no previous invocation, state, settledState, and result will all be undefined.
*
* @param lock The object (such as a string, a number, or `this` in a class) used to identify the lock.
* @param operation The function that performs the computation and returns a Promise.
* @returns The result of the operation function.
*/
static synchronized<T>(lock: unknown, operation: (previousState: PromiseState | undefined, previousSettledState: PromiseState | undefined, previousResult: any) => Promise<T>): Promise<T>;
static synchronized<T>(lock: any, operation: (previousState: PromiseState | undefined, previousSettledState: PromiseState | undefined, previousResult: any) => Promise<T>): Promise<T>;
/**
* This is just another spelling of {@link PromiseUtils.synchronized}.
* @param lock the object (could be a string, a number, or `this` in a class) that is used to apply the lock
* @param operation function for doing the computation and returning a Promise
* @returns the result of the operation function
* @param lock The object (such as a string, a number, or `this` in a class) used to identify the lock.
* @param operation The function that performs the computation and returns a Promise.
* @returns The result of the operation function.
*/
static synchronised<T>(lock: unknown, operation: (previousState: PromiseState | undefined, previousSettledState: PromiseState | undefined, previousResult: any) => Promise<T>): Promise<T>;
static synchronised<T>(lock: any, operation: (previousState: PromiseState | undefined, previousSettledState: PromiseState | undefined, previousResult: any) => Promise<T>): Promise<T>;
}

@@ -212,2 +244,6 @@ /**

/**
* See {@link PromiseUtils.withConcurrency} for full documentation.
*/
export declare const withConcurrency: typeof PromiseUtils.withConcurrency;
/**
* See {@link PromiseUtils.inParallel} for full documentation.

@@ -214,0 +250,0 @@ */

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.promiseState = exports.synchronised = exports.synchronized = exports.timeoutReject = exports.timeoutResolve = exports.delayedReject = exports.delayedResolve = exports.inParallel = exports.withRetry = exports.repeat = exports.PromiseUtils = exports.PromiseState = exports.EXPONENTIAL_SEQUENCE = exports.FIBONACCI_SEQUENCE = void 0;
exports.promiseState = exports.synchronised = exports.synchronized = exports.timeoutReject = exports.timeoutResolve = exports.delayedReject = exports.delayedResolve = exports.inParallel = exports.withConcurrency = exports.withRetry = exports.repeat = exports.PromiseUtils = exports.PromiseState = exports.EXPONENTIAL_SEQUENCE = exports.FIBONACCI_SEQUENCE = void 0;
/**

@@ -39,4 +39,4 @@ * Array of 25 Fibonacci numbers starting from 1 up to 317811.

/**
* Do an operation repeatedly and collect all the results.
* This function is useful for client side pagination.
* Executes an operation repeatedly and collects all the results.
* This function is very useful for many scenarios, such like client-side pagination.
*

@@ -51,15 +51,15 @@ * @example

*
* @template Result type of the operation result
* @template Param type of the input to the operation, normally the input is a paging parameter
* @template Collection type of the returned value of this function
* @template Result The type of the operation result.
* @template Param The type of the input to the operation, typically a paging parameter.
* @template Collection The type of the collection returned by this function.
*
* @param operation a function that takes paging parameter as input and outputs a result, normally the operation supports paging
* @param nextParameter The function for calculating next parameter from the operation result.
* Normally the parameter controls paging,
* This function should return null when next invocation of the operation function is not desired.
* If next invocation is desired, the return value of this function can be a Promise or not a Promise.
* @param collect the function for merging operation result into the collection
* @param initialCollection initial collection which would be the first argument passed into the first invocation of the collect function
* @param initialParameter the parameter for the first operation
* @returns Promise of collection of all the results returned by the operation function
* @param operation A function that takes a parameter as input and returns a result. Typically, the parameter has optional fields to control paging.
* @param nextParameter A function for calculating the next parameter from the operation result.
* Normally, this parameter controls paging.
* This function should return null when no further invocation of the operation function is desired.
* If further invocation is desired, the return value of this function can be a Promise or a non-Promise value.
* @param collect A function for merging the operation result into the collection.
* @param initialCollection The initial collection, which will be the first argument passed to the first invocation of the collect function.
* @param initialParameter The parameter for the first operation.
* @returns A promise that resolves to a collection of all the results returned by the operation function.
*

@@ -82,3 +82,3 @@ */

/**
* Do an operation repeatedly until a criteria is met.
* Repeatedly performs an operation until a specified criteria is met.
*

@@ -90,16 +90,15 @@ * @example

*
* @template Result type of the operation result
* @template TError type of the possible error that could be generated by the operation
* @template Result Type of the operation result.
* @template TError Type of the possible error that could be generated by the operation.
*
* @param operation a function that outputs a Promise result, normally the operation does not use its arguments
* @param backoff Array of retry backoff periods (unit: milliseconds) or function for calculating them.
* If retry is desired, before making next call to the operation the desired backoff period would be waited.
* If the array runs out of elements or the function returns `undefined` or either the array or the function returns a negative number,
* there would be no further call to the operation.
* The `attempt` argument passed into backoff function starts from 1 because the function is called right after the first attempt and before the first retry.
* @param shouldRetry Predicate function for deciding whether another call to the operation should happen.
* If this argument is not defined, retry would happen whenever the operation rejects with an error.
* `shouldRetry` would be evaluated before `backoff`.
* The `attempt` argument passed into shouldRetry function starts from 1.
* @returns Promise of the operation result potentially with retries already applied
* @param operation A function that outputs a Promise result. Typically, the operation does not use its arguments.
* @param backoff An array of retry backoff periods (in milliseconds) or a function for calculating them.
* If retry is desired, the specified backoff period is waited before the next call to the operation.
* If the array runs out of elements or the function returns `undefined` or a negative number, no further calls to the operation will be made.
* The `attempt` argument passed to the backoff function starts from 1, as it is called immediately after the first attempt and before the first retry.
* @param shouldRetry A predicate function for deciding whether another call to the operation should occur.
* If this argument is not defined, a retry will occur whenever the operation rejects with an error.
* The `shouldRetry` function is evaluated before the `backoff`.
* The `attempt` argument passed to the shouldRetry function starts from 1.
* @returns A promise of the operation result, potentially with retries applied.
*/

@@ -125,14 +124,42 @@ static async withRetry(operation, backoff, shouldRetry = (previousError, _previousResult, _attempt) => previousError !== undefined) {

/**
* Run multiple jobs/operations in parallel.
* Executes multiple jobs/operations with a specified level of concurrency.
*
* By default this function does not throw / reject with error when any of the job/operation fails.
* Operation errors are returned together with operation results in the same returned array.
* That also means this function only returns when all the jobs/operations settle (either resolve or reject).
* Unlike `inParallel(...)`, this function may throw or reject an error when a job/operation fails.
* When an error is re-thrown, remaining operations will not be executed.
* If you want all the operations to always be executed, use {@link PromiseUtils.inParallel} instead.
*
* However, if options.abortOnError is true, this function throws / rejects with error when any of the job/operation fails.
* That also means, some of the jobs/operations may not get the chance to be executed if one of them fails.
* @example
* // At any time, there would be no more than 5 concurrency API calls. Error would be re-thrown immediately when it occurs.
* const attributes = await PromiseUtils.withConcurrency(5, topicArns, async (topicArn) => {
* const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;
* return topicAttributes;
* });
*
*
* @template Data The type of the job data, typically an Array.
* @template Result The type of the return value from the operation function.
*
* @param concurrency The number of jobs/operations to run concurrently.
* @param jobs The job data to be processed. This function can handle an infinite or unknown number of elements safely.
* @param operation The function that processes job data asynchronously.
* @returns A promise that resolves to an array containing the results from the operation function.
* The results in the returned array are in the same order as the corresponding elements in the jobs array.
*/
static async withConcurrency(concurrency, jobs, operation) {
return (0, exports.inParallel)(concurrency, jobs, operation);
}
/**
* Executes multiple jobs/operations in parallel. By default, all operations are executed regardless of any failures.
* In most cases, using {@link PromiseUtils.withConcurrency} might be more convenient.
*
* By default, this function does not throw or reject an error when any job/operation fails.
* Errors from operations are returned alongside results in the returned array.
* This function only resolves when all jobs/operations are settled (either resolved or rejected).
*
* If `options.abortOnError` is set to true, this function throws (or rejects with) an error immediately when any job/operation fails.
* In this mode, some jobs/operations may not be executed if one fails.
*
* @example
* // Capture errors in the returned array
* const attributesAndPossibleErrors = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
* const attributesAndPossibleErrors: Array<JobResult|JobError> = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
* const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;

@@ -150,13 +177,14 @@ * return topicAttributes;

*
* @template Data Type of the job data, usually it would be an Array
* @template Result Type of the return value of the operation function
* @template Data The type of the job data, typically an Array.
* @template Result The type of the return value from the operation function.
* @template TError The type for the error that could be thrown from the operation function, defaults to `Result`.
*
* @param parallelism how many jobs/operations can be running at the same time
* @param jobs job data which will be the input to operation function.
* This function is safe when there are infinite unknown number of elements in the job data.
* @param operation the function that turns job data into result asynchronously
* @param options Options for controlling the behavior of this function.
* @returns Promise of void if the operation function does not return a value,
* or promise of an array containing outcomes from the operation function.
* In the returned array containing outcomes, each element is either the fulfilled result, or the rejected error/reason.
* @param parallelism The number of jobs/operations to run concurrently.
* @param jobs The job data to be processed. This function can safely handle an infinite or unknown number of elements.
* @param operation The function that processes job data asynchronously.
* @param options Options to control the function's behavior.
* @param options.abortOnError If true, the function aborts and throws an error on the first failed operation.
* @returns A promise that resolves to an array containing the results of the operations.
* Each element is either a fulfilled result or a rejected error/reason.
* The results or errors in the returned array are in the same order as the corresponding elements in the jobs array.
*/

@@ -187,6 +215,7 @@ static async inParallel(parallelism, jobs, operation, options) {

/**
* Create a Promise that resolves after number of milliseconds specified
* @param ms number of milliseconds after which the created Promise would resolve
* @param result the result to be resolved for the Promise, or a function that supplies the result.
* @returns the new Promise created
* Creates a Promise that resolves after a specified number of milliseconds.
*
* @param ms The number of milliseconds after which the created Promise will resolve.
* @param result The result to be resolved by the Promise, or a function that supplies the result.
* @returns A new Promise that resolves with the specified result after the specified delay.
*/

@@ -198,7 +227,8 @@ static delayedResolve(ms, result) {

/**
* Create a Promise that rejects after number of milliseconds specified.
* @param ms number of milliseconds after which the created Promise would reject
* @param reason the reason of the rejection for the Promise, or a function that supplies the reason.
* If the reason ends up to be a rejected Promise, then the outcome (could be fulfilled or rejected) of it will be the reject reason of the Promise returned.
* @returns the new Promise created
* Creates a Promise that rejects after a specified number of milliseconds.
*
* @param ms The number of milliseconds after which the created Promise will reject.
* @param reason The reason for the rejection, or a function that supplies the reason.
* If the reason is a rejected Promise, the outcome of it will be the rejection reason of the returned Promise.
* @returns A new Promise that rejects with the specified reason after the specified delay.
*/

@@ -214,11 +244,12 @@ static delayedReject(ms, reason) {

* Applies a timeout to a Promise or a function that returns a Promise.
* If the timeout occurs, resolves to the specified result.
* If the timeout doesn't occur, the resolved result or rejection reason of the original Promise will be the outcome of the Promise returned from this function.
* If the 'result' parameter is a function and timeout doesn't occur, the function won't be called.
* The rejection of the 'operation' parameter is not handled by this function, you may want to handle it outside of this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously".
* If the timeout occurs, the returned Promise resolves to the specified result.
* If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
* If the `result` parameter is a function and the timeout does not occur, the function will not be called.
* Note: The rejection of the `operation` parameter is not handled by this function.
* You may want to handle it outside this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously."
*
* @param operation The original Promise or a function that returns a Promise for which the timeout will be applied.
* @param operation The original Promise or a function that returns a Promise to which the timeout will be applied.
* @param ms The number of milliseconds for the timeout.
* @param result The result to be resolved with if the timeout occurs, or a function that supplies the result.
* @return A new Promise that resolves to the specified result if the timeout occurs.
* @param result The result to resolve with if the timeout occurs, or a function that supplies the result.
* @returns A new Promise that resolves to the specified result if the timeout occurs.
*/

@@ -237,11 +268,11 @@ static timeoutResolve(operation, ms, result) {

* Applies a timeout to a Promise or a function that returns a Promise.
* If the timeout occurs, rejects with the specified reason.
* If the timeout doesn't occur, the resolved result or rejection reason of the original Promise will be the outcome of the Promise returned from this function.
* If the 'reason' parameter is a function and timeout doesn't occur, the function won't be called.
* The rejection of the 'operation' parameter is not handled by this function, you may want to handle it outside of this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously".
* If the timeout occurs, the returned Promise rejects with the specified reason.
* If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
* If the `rejectReason` parameter is a function and the timeout does not occur, the function will not be called.
* Note: The rejection of the `operation` parameter is not handled by this function. You may want to handle it outside this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously."
*
* @param operation The original Promise or a function that returns a Promise for which the timeout will be applied.
* @param operation The original Promise or a function that returns a Promise to which the timeout will be applied.
* @param ms The number of milliseconds for the timeout.
* @param rejectReason The reason to reject with if the timeout occurs, or a function that supplies the reason.
* @return A new Promise that rejects with the specified reason if the timeout occurs.
* @returns A new Promise that rejects with the specified reason if the timeout occurs.
*/

@@ -259,6 +290,7 @@ static timeoutReject(operation, ms, rejectReason) {

/**
* Get the state of the Promise.
* Please note that the returned value is a Promise, although it resolves immediately.
* @param p the Promise for which we would like to know its state
* @return A Promise that resolves immediately containing the state of the input Promise
* Retrieves the state of the specified Promise.
* Note: The returned value is a Promise that resolves immediately.
*
* @param p The Promise whose state is to be determined.
* @returns A Promise that resolves immediately with the state of the input Promise.
*/

@@ -271,10 +303,12 @@ static promiseState(p) {

/**
* Equivalent of `synchronized` in Java.
* In any situation there's no concurrent execution of any operation function associated with the same lock.
* The operation function has access to the state (when `synchronized` is called), settledState (when the operation function is called),
* and result (could be the fulfilled result or the rejected reason) of the previous operation.
* In case there is no previous invocation, state, settledState and result would all be undefined.
* @param lock the object (could be a string, a number, or `this` in a class) that is used to apply the lock
* @param operation function for doing the computation and returning a Promise
* @returns the result of the operation function
* Provides mutual exclusion similar to `synchronized` in Java.
* Ensures no concurrent execution of any operation function associated with the same lock.
* The operation function has access to the state (when `synchronized` is called),
* settledState (when the operation function is called),
* and result (either the fulfilled result or the rejected reason) of the previous operation.
* If there is no previous invocation, state, settledState, and result will all be undefined.
*
* @param lock The object (such as a string, a number, or `this` in a class) used to identify the lock.
* @param operation The function that performs the computation and returns a Promise.
* @returns The result of the operation function.
*/

@@ -308,5 +342,5 @@ static async synchronized(lock, operation) {

* This is just another spelling of {@link PromiseUtils.synchronized}.
* @param lock the object (could be a string, a number, or `this` in a class) that is used to apply the lock
* @param operation function for doing the computation and returning a Promise
* @returns the result of the operation function
* @param lock The object (such as a string, a number, or `this` in a class) used to identify the lock.
* @param operation The function that performs the computation and returns a Promise.
* @returns The result of the operation function.
*/

@@ -328,2 +362,6 @@ static async synchronised(lock, operation) {

/**
* See {@link PromiseUtils.withConcurrency} for full documentation.
*/
exports.withConcurrency = PromiseUtils.withConcurrency;
/**
* See {@link PromiseUtils.inParallel} for full documentation.

@@ -330,0 +368,0 @@ */

{
"name": "@handy-common-utils/promise-utils",
"version": "1.4.1",
"version": "1.5.0",
"description": "Promise related utilities",

@@ -19,3 +19,3 @@ "scripts": {

"devDependencies": {
"@handy-common-utils/dev-dependencies-mocha": "^1.3.1",
"@handy-common-utils/dev-dependencies-mocha": "^1.5.4",
"@types/node": "^18.17.1"

@@ -22,0 +22,0 @@ },

# @handy-common-utils/promise-utils
These Promise related utilities have 100% test coverage. The package is tiny because there is no dependency on any other package.
Functions provided are `repeat`, `withRetry`, `inParallel`, `delayedResolve`, `delayedReject`, `timeoutResolve`, `timeoutReject`, `promiseState`, `synchronized`, etc.
These Promise-related utilities boast 100% test coverage, ensuring robust reliability.
The package, free of external dependencies, offers essential functions such as:
- `repeat`: Executes an operation repeatedly, very useful to collect all results through pagination.
- `withRetry`: Retries an operation until a specified condition is met.
- `withConcurrency`: Executes multiple operations with specified level of concurrency, and abort remaining operations when an error happens.
- `inParallel`: Executes multiple operations with specified level of concurrency, all operations are guaranteed to be executed regardless of any possible error.
- `delayedResolve`: Creates a Promise that resolves after a specified delay.
- `delayedReject`: Creates a Promise that rejects after a specified delay.
- `timeoutResolve`: Applies a timeout to a Promise and resolves with a specified result if the timeout occurs.
- `timeoutReject`: Applies a timeout to a Promise and rejects with a specified error/reason if the timeout occurs.
- `promiseState`: Retrieves the state of a Promise.
- `synchronized`: Provides mutual exclusion for concurrent operations using a lock mechanism, similar to `synchronized` in Java.
[![Version](https://img.shields.io/npm/v/@handy-common-utils/promise-utils.svg)](https://npmjs.org/package/@handy-common-utils/promise-utils)

@@ -62,3 +73,2 @@ [![Downloads/week](https://img.shields.io/npm/dw/@handy-common-utils/promise-utils.svg)](https://npmjs.org/package/@handy-common-utils/promise-utils)

// inParallel(...)
// Capture errors in the returned array

@@ -73,3 +83,3 @@ const attributesAndPossibleErrors = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {

try {
results = await PromiseUtils.inParallel(100, jobs, async (job) => processor.process(job), { abortOnError: true });
results = await PromiseUtils.withConcurrency(100, jobs, async (job) => processor.process(job));
} catch (error) {

@@ -140,3 +150,3 @@ // handle the error

▸ **delayedReject**<`T`, `R`\>(`ms`, `reason`): `Promise`<`T`\>
▸ **delayedReject**\<`T`, `R`\>(`ms`, `reason`): `Promise`\<`T`\>

@@ -157,7 +167,7 @@ See [delayedReject](#delayedreject) for full documentation.

| `ms` | `number` |
| `reason` | `R` \| `PromiseLike`<`R`\> \| () => `R` \| `PromiseLike`<`R`\> |
| `reason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> |
##### Returns
`Promise`<`T`\>
`Promise`\<`T`\>

@@ -168,3 +178,3 @@ ___

▸ **delayedResolve**<`T`\>(`ms`, `result?`): `Promise`<`T`\>
▸ **delayedResolve**\<`T`\>(`ms`, `result?`): `Promise`\<`T`\>

@@ -184,7 +194,7 @@ See [delayedResolve](#delayedresolve) for full documentation.

| `ms` | `number` |
| `result?` | `T` \| `PromiseLike`<`T`\> \| () => `T` \| `PromiseLike`<`T`\> |
| `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> |
##### Returns
`Promise`<`T`\>
`Promise`\<`T`\>

@@ -195,3 +205,3 @@ ___

▸ **inParallel**<`Data`, `Result`, `TError`\>(`parallelism`, `jobs`, `operation`, `options?`): `Promise`<(`Result` \| `TError`)[]\>
▸ **inParallel**\<`Data`, `Result`, `TError`\>(`parallelism`, `jobs`, `operation`, `options?`): `Promise`\<(`Result` \| `TError`)[]\>

@@ -213,4 +223,4 @@ See [inParallel](#inparallel) for full documentation.

| `parallelism` | `number` |
| `jobs` | `Iterable`<`Data`\> |
| `operation` | (`job`: `Data`, `index`: `number`) => `Promise`<`Result`\> |
| `jobs` | `Iterable`\<`Data`\> |
| `operation` | (`job`: `Data`, `index`: `number`) => `Promise`\<`Result`\> |
| `options?` | `Object` |

@@ -221,3 +231,3 @@ | `options.abortOnError` | `boolean` |

`Promise`<(`Result` \| `TError`)[]\>
`Promise`\<(`Result` \| `TError`)[]\>

@@ -228,3 +238,3 @@ ___

▸ **promiseState**(`p`): `Promise`<[`PromiseState`](#enumspromisestatemd)\>
▸ **promiseState**(`p`): `Promise`\<[`PromiseState`](#enumspromisestatemd)\>

@@ -237,7 +247,7 @@ See [promiseState](#promisestate) for full documentation.

| :------ | :------ |
| `p` | `Promise`<`any`\> |
| `p` | `Promise`\<`any`\> |
##### Returns
`Promise`<[`PromiseState`](#enumspromisestatemd)\>
`Promise`\<[`PromiseState`](#enumspromisestatemd)\>

@@ -248,3 +258,3 @@ ___

▸ **repeat**<`Result`, `Param`, `Collection`\>(`operation`, `nextParameter`, `collect`, `initialCollection`, `initialParameter?`): `Promise`<`Collection`\>
▸ **repeat**\<`Result`, `Param`, `Collection`\>(`operation`, `nextParameter`, `collect`, `initialCollection`, `initialParameter?`): `Promise`\<`Collection`\>

@@ -265,11 +275,11 @@ See [repeat](#repeat) for full documentation.

| :------ | :------ |
| `operation` | (`parameter`: `Partial`<`Param`\>) => `Promise`<`Result`\> |
| `nextParameter` | (`response`: `Result`) => ``null`` \| `Partial`<`Param`\> \| `Promise`<`Partial`<`Param`\>\> |
| `operation` | (`parameter`: `Partial`\<`Param`\>) => `Promise`\<`Result`\> |
| `nextParameter` | (`response`: `Result`) => ``null`` \| `Partial`\<`Param`\> \| `Promise`\<`Partial`\<`Param`\>\> |
| `collect` | (`collection`: `Collection`, `result`: `Result`) => `Collection` |
| `initialCollection` | `Collection` |
| `initialParameter` | `Partial`<`Param`\> |
| `initialParameter` | `Partial`\<`Param`\> |
##### Returns
`Promise`<`Collection`\>
`Promise`\<`Collection`\>

@@ -280,3 +290,3 @@ ___

▸ **synchronised**<`T`\>(`lock`, `operation`): `Promise`<`T`\>
▸ **synchronised**\<`T`\>(`lock`, `operation`): `Promise`\<`T`\>

@@ -295,8 +305,8 @@ See [synchronised](#synchronised) for full documentation.

| :------ | :------ |
| `lock` | `unknown` |
| `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`<`T`\> |
| `lock` | `any` |
| `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`\<`T`\> |
##### Returns
`Promise`<`T`\>
`Promise`\<`T`\>

@@ -307,3 +317,3 @@ ___

▸ **synchronized**<`T`\>(`lock`, `operation`): `Promise`<`T`\>
▸ **synchronized**\<`T`\>(`lock`, `operation`): `Promise`\<`T`\>

@@ -322,8 +332,8 @@ See [synchronized](#synchronized) for full documentation.

| :------ | :------ |
| `lock` | `unknown` |
| `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`<`T`\> |
| `lock` | `any` |
| `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`\<`T`\> |
##### Returns
`Promise`<`T`\>
`Promise`\<`T`\>

@@ -334,3 +344,3 @@ ___

▸ **timeoutReject**<`T`, `R`\>(`operation`, `ms`, `rejectReason`): `Promise`<`T`\>
▸ **timeoutReject**\<`T`, `R`\>(`operation`, `ms`, `rejectReason`): `Promise`\<`T`\>

@@ -350,9 +360,9 @@ See [timeoutReject](#timeoutreject) for full documentation.

| :------ | :------ |
| `operation` | `Promise`<`T`\> \| () => `Promise`<`T`\> |
| `operation` | `Promise`\<`T`\> \| () => `Promise`\<`T`\> |
| `ms` | `number` |
| `rejectReason` | `R` \| `PromiseLike`<`R`\> \| () => `R` \| `PromiseLike`<`R`\> |
| `rejectReason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> |
##### Returns
`Promise`<`T`\>
`Promise`\<`T`\>

@@ -363,3 +373,3 @@ ___

▸ **timeoutResolve**<`T`\>(`operation`, `ms`, `result?`): `Promise`<`T`\>
▸ **timeoutResolve**\<`T`\>(`operation`, `ms`, `result?`): `Promise`\<`T`\>

@@ -378,15 +388,42 @@ See [timeoutResolve](#timeoutresolve) for full documentation.

| :------ | :------ |
| `operation` | `Promise`<`T`\> \| () => `Promise`<`T`\> |
| `operation` | `Promise`\<`T`\> \| () => `Promise`\<`T`\> |
| `ms` | `number` |
| `result?` | `T` \| `PromiseLike`<`T`\> \| () => `T` \| `PromiseLike`<`T`\> |
| `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> |
##### Returns
`Promise`<`T`\>
`Promise`\<`T`\>
___
#### withConcurrency
▸ **withConcurrency**\<`Data`, `Result`\>(`concurrency`, `jobs`, `operation`): `Promise`\<`Result`[]\>
See [withConcurrency](#withconcurrency) for full documentation.
##### Type parameters
| Name |
| :------ |
| `Data` |
| `Result` |
##### Parameters
| Name | Type |
| :------ | :------ |
| `concurrency` | `number` |
| `jobs` | `Iterable`\<`Data`\> |
| `operation` | (`job`: `Data`, `index`: `number`) => `Promise`\<`Result`\> |
##### Returns
`Promise`\<`Result`[]\>
___
#### withRetry
▸ **withRetry**<`Result`, `TError`\>(`operation`, `backoff`, `shouldRetry?`): `Promise`<`Result`\>
▸ **withRetry**\<`Result`, `TError`\>(`operation`, `backoff`, `shouldRetry?`): `Promise`\<`Result`\>

@@ -406,3 +443,3 @@ See [withRetry](#withretry) for full documentation.

| :------ | :------ |
| `operation` | (`attempt`: `number`, `previousResult`: `undefined` \| `Result`, `previousError`: `undefined` \| `TError`) => `Promise`<`Result`\> |
| `operation` | (`attempt`: `number`, `previousResult`: `undefined` \| `Result`, `previousError`: `undefined` \| `TError`) => `Promise`\<`Result`\> |
| `backoff` | `number`[] \| (`attempt`: `number`, `previousResult`: `undefined` \| `Result`, `previousError`: `undefined` \| `TError`) => `undefined` \| `number` |

@@ -413,3 +450,3 @@ | `shouldRetry` | (`previousError`: `undefined` \| `TError`, `previousResult`: `undefined` \| `Result`, `attempt`: `number`) => `boolean` |

`Promise`<`Result`\>
`Promise`\<`Result`\>

@@ -433,5 +470,5 @@ ## Classes

▸ `Static` **delayedReject**<`T`, `R`\>(`ms`, `reason`): `Promise`<`T`\>
▸ `Static` **delayedReject**\<`T`, `R`\>(`ms`, `reason`): `Promise`\<`T`\>
Create a Promise that rejects after number of milliseconds specified.
Creates a Promise that rejects after a specified number of milliseconds.

@@ -449,10 +486,10 @@ ###### Type parameters

| :------ | :------ | :------ |
| `ms` | `number` | number of milliseconds after which the created Promise would reject |
| `reason` | `R` \| `PromiseLike`<`R`\> \| () => `R` \| `PromiseLike`<`R`\> | the reason of the rejection for the Promise, or a function that supplies the reason. If the reason ends up to be a rejected Promise, then the outcome (could be fulfilled or rejected) of it will be the reject reason of the Promise returned. |
| `ms` | `number` | The number of milliseconds after which the created Promise will reject. |
| `reason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> | The reason for the rejection, or a function that supplies the reason. If the reason is a rejected Promise, the outcome of it will be the rejection reason of the returned Promise. |
###### Returns
`Promise`<`T`\>
`Promise`\<`T`\>
the new Promise created
A new Promise that rejects with the specified reason after the specified delay.

@@ -463,5 +500,5 @@ ___

▸ `Static` **delayedResolve**<`T`\>(`ms`, `result?`): `Promise`<`T`\>
▸ `Static` **delayedResolve**\<`T`\>(`ms`, `result?`): `Promise`\<`T`\>
Create a Promise that resolves after number of milliseconds specified
Creates a Promise that resolves after a specified number of milliseconds.

@@ -478,10 +515,10 @@ ###### Type parameters

| :------ | :------ | :------ |
| `ms` | `number` | number of milliseconds after which the created Promise would resolve |
| `result?` | `T` \| `PromiseLike`<`T`\> \| () => `T` \| `PromiseLike`<`T`\> | the result to be resolved for the Promise, or a function that supplies the result. |
| `ms` | `number` | The number of milliseconds after which the created Promise will resolve. |
| `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> | The result to be resolved by the Promise, or a function that supplies the result. |
###### Returns
`Promise`<`T`\>
`Promise`\<`T`\>
the new Promise created
A new Promise that resolves with the specified result after the specified delay.

@@ -492,12 +529,13 @@ ___

▸ `Static` **inParallel**<`Data`, `Result`, `TError`\>(`parallelism`, `jobs`, `operation`, `options?`): `Promise`<(`Result` \| `TError`)[]\>
▸ `Static` **inParallel**\<`Data`, `Result`, `TError`\>(`parallelism`, `jobs`, `operation`, `options?`): `Promise`\<(`Result` \| `TError`)[]\>
Run multiple jobs/operations in parallel.
Executes multiple jobs/operations in parallel. By default, all operations are executed regardless of any failures.
In most cases, using [withConcurrency](#withconcurrency) might be more convenient.
By default this function does not throw / reject with error when any of the job/operation fails.
Operation errors are returned together with operation results in the same returned array.
That also means this function only returns when all the jobs/operations settle (either resolve or reject).
By default, this function does not throw or reject an error when any job/operation fails.
Errors from operations are returned alongside results in the returned array.
This function only resolves when all jobs/operations are settled (either resolved or rejected).
However, if options.abortOnError is true, this function throws / rejects with error when any of the job/operation fails.
That also means, some of the jobs/operations may not get the chance to be executed if one of them fails.
If `options.abortOnError` is set to true, this function throws (or rejects with) an error immediately when any job/operation fails.
In this mode, some jobs/operations may not be executed if one fails.

@@ -508,5 +546,5 @@ ###### Type parameters

| :------ | :------ | :------ |
| `Data` | `Data` | Type of the job data, usually it would be an Array |
| `Result` | `Result` | Type of the return value of the operation function |
| `TError` | `Result` | - |
| `Data` | `Data` | The type of the job data, typically an Array. |
| `Result` | `Result` | The type of the return value from the operation function. |
| `TError` | `Result` | The type for the error that could be thrown from the operation function, defaults to `Result`. |

@@ -517,15 +555,15 @@ ###### Parameters

| :------ | :------ | :------ |
| `parallelism` | `number` | how many jobs/operations can be running at the same time |
| `jobs` | `Iterable`<`Data`\> | job data which will be the input to operation function. This function is safe when there are infinite unknown number of elements in the job data. |
| `operation` | (`job`: `Data`, `index`: `number`) => `Promise`<`Result`\> | the function that turns job data into result asynchronously |
| `options?` | `Object` | Options for controlling the behavior of this function. |
| `options.abortOnError` | `boolean` | - |
| `parallelism` | `number` | The number of jobs/operations to run concurrently. |
| `jobs` | `Iterable`\<`Data`\> | The job data to be processed. This function can safely handle an infinite or unknown number of elements. |
| `operation` | (`job`: `Data`, `index`: `number`) => `Promise`\<`Result`\> | The function that processes job data asynchronously. |
| `options?` | `Object` | Options to control the function's behavior. |
| `options.abortOnError` | `boolean` | If true, the function aborts and throws an error on the first failed operation. |
###### Returns
`Promise`<(`Result` \| `TError`)[]\>
`Promise`\<(`Result` \| `TError`)[]\>
Promise of void if the operation function does not return a value,
or promise of an array containing outcomes from the operation function.
In the returned array containing outcomes, each element is either the fulfilled result, or the rejected error/reason.
A promise that resolves to an array containing the results of the operations.
Each element is either a fulfilled result or a rejected error/reason.
The results or errors in the returned array are in the same order as the corresponding elements in the jobs array.

@@ -536,3 +574,3 @@ **`Example`**

// Capture errors in the returned array
const attributesAndPossibleErrors = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
const attributesAndPossibleErrors: Array<JobResult|JobError> = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;

@@ -555,6 +593,6 @@ return topicAttributes;

▸ `Static` **promiseState**(`p`): `Promise`<[`PromiseState`](#enumspromisestatemd)\>
▸ `Static` **promiseState**(`p`): `Promise`\<[`PromiseState`](#enumspromisestatemd)\>
Get the state of the Promise.
Please note that the returned value is a Promise, although it resolves immediately.
Retrieves the state of the specified Promise.
Note: The returned value is a Promise that resolves immediately.

@@ -565,9 +603,9 @@ ###### Parameters

| :------ | :------ | :------ |
| `p` | `Promise`<`any`\> | the Promise for which we would like to know its state |
| `p` | `Promise`\<`any`\> | The Promise whose state is to be determined. |
###### Returns
`Promise`<[`PromiseState`](#enumspromisestatemd)\>
`Promise`\<[`PromiseState`](#enumspromisestatemd)\>
A Promise that resolves immediately containing the state of the input Promise
A Promise that resolves immediately with the state of the input Promise.

@@ -578,6 +616,6 @@ ___

▸ `Static` **repeat**<`Result`, `Param`, `Collection`\>(`operation`, `nextParameter`, `collect`, `initialCollection`, `initialParameter?`): `Promise`<`Collection`\>
▸ `Static` **repeat**\<`Result`, `Param`, `Collection`\>(`operation`, `nextParameter`, `collect`, `initialCollection`, `initialParameter?`): `Promise`\<`Collection`\>
Do an operation repeatedly and collect all the results.
This function is useful for client side pagination.
Executes an operation repeatedly and collects all the results.
This function is very useful for many scenarios, such like client-side pagination.

@@ -588,5 +626,5 @@ ###### Type parameters

| :------ | :------ |
| `Result` | type of the operation result |
| `Param` | type of the input to the operation, normally the input is a paging parameter |
| `Collection` | type of the returned value of this function |
| `Result` | The type of the operation result. |
| `Param` | The type of the input to the operation, typically a paging parameter. |
| `Collection` | The type of the collection returned by this function. |

@@ -597,13 +635,13 @@ ###### Parameters

| :------ | :------ | :------ |
| `operation` | (`parameter`: `Partial`<`Param`\>) => `Promise`<`Result`\> | a function that takes paging parameter as input and outputs a result, normally the operation supports paging |
| `nextParameter` | (`response`: `Result`) => ``null`` \| `Partial`<`Param`\> \| `Promise`<`Partial`<`Param`\>\> | The function for calculating next parameter from the operation result. Normally the parameter controls paging, This function should return null when next invocation of the operation function is not desired. If next invocation is desired, the return value of this function can be a Promise or not a Promise. |
| `collect` | (`collection`: `Collection`, `result`: `Result`) => `Collection` | the function for merging operation result into the collection |
| `initialCollection` | `Collection` | initial collection which would be the first argument passed into the first invocation of the collect function |
| `initialParameter` | `Partial`<`Param`\> | the parameter for the first operation |
| `operation` | (`parameter`: `Partial`\<`Param`\>) => `Promise`\<`Result`\> | A function that takes a parameter as input and returns a result. Typically, the parameter has optional fields to control paging. |
| `nextParameter` | (`response`: `Result`) => ``null`` \| `Partial`\<`Param`\> \| `Promise`\<`Partial`\<`Param`\>\> | A function for calculating the next parameter from the operation result. Normally, this parameter controls paging. This function should return null when no further invocation of the operation function is desired. If further invocation is desired, the return value of this function can be a Promise or a non-Promise value. |
| `collect` | (`collection`: `Collection`, `result`: `Result`) => `Collection` | A function for merging the operation result into the collection. |
| `initialCollection` | `Collection` | The initial collection, which will be the first argument passed to the first invocation of the collect function. |
| `initialParameter` | `Partial`\<`Param`\> | The parameter for the first operation. |
###### Returns
`Promise`<`Collection`\>
`Promise`\<`Collection`\>
Promise of collection of all the results returned by the operation function
A promise that resolves to a collection of all the results returned by the operation function.

@@ -625,3 +663,3 @@ **`Example`**

▸ `Static` **synchronised**<`T`\>(`lock`, `operation`): `Promise`<`T`\>
▸ `Static` **synchronised**\<`T`\>(`lock`, `operation`): `Promise`\<`T`\>

@@ -640,10 +678,10 @@ This is just another spelling of [synchronized](#synchronized).

| :------ | :------ | :------ |
| `lock` | `unknown` | the object (could be a string, a number, or `this` in a class) that is used to apply the lock |
| `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`<`T`\> | function for doing the computation and returning a Promise |
| `lock` | `any` | The object (such as a string, a number, or `this` in a class) used to identify the lock. |
| `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`\<`T`\> | The function that performs the computation and returns a Promise. |
###### Returns
`Promise`<`T`\>
`Promise`\<`T`\>
the result of the operation function
The result of the operation function.

@@ -654,9 +692,10 @@ ___

▸ `Static` **synchronized**<`T`\>(`lock`, `operation`): `Promise`<`T`\>
▸ `Static` **synchronized**\<`T`\>(`lock`, `operation`): `Promise`\<`T`\>
Equivalent of `synchronized` in Java.
In any situation there's no concurrent execution of any operation function associated with the same lock.
The operation function has access to the state (when `synchronized` is called), settledState (when the operation function is called),
and result (could be the fulfilled result or the rejected reason) of the previous operation.
In case there is no previous invocation, state, settledState and result would all be undefined.
Provides mutual exclusion similar to `synchronized` in Java.
Ensures no concurrent execution of any operation function associated with the same lock.
The operation function has access to the state (when `synchronized` is called),
settledState (when the operation function is called),
and result (either the fulfilled result or the rejected reason) of the previous operation.
If there is no previous invocation, state, settledState, and result will all be undefined.

@@ -673,10 +712,10 @@ ###### Type parameters

| :------ | :------ | :------ |
| `lock` | `unknown` | the object (could be a string, a number, or `this` in a class) that is used to apply the lock |
| `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`<`T`\> | function for doing the computation and returning a Promise |
| `lock` | `any` | The object (such as a string, a number, or `this` in a class) used to identify the lock. |
| `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`\<`T`\> | The function that performs the computation and returns a Promise. |
###### Returns
`Promise`<`T`\>
`Promise`\<`T`\>
the result of the operation function
The result of the operation function.

@@ -687,9 +726,9 @@ ___

▸ `Static` **timeoutReject**<`T`, `R`\>(`operation`, `ms`, `rejectReason`): `Promise`<`T`\>
▸ `Static` **timeoutReject**\<`T`, `R`\>(`operation`, `ms`, `rejectReason`): `Promise`\<`T`\>
Applies a timeout to a Promise or a function that returns a Promise.
If the timeout occurs, rejects with the specified reason.
If the timeout doesn't occur, the resolved result or rejection reason of the original Promise will be the outcome of the Promise returned from this function.
If the 'reason' parameter is a function and timeout doesn't occur, the function won't be called.
The rejection of the 'operation' parameter is not handled by this function, you may want to handle it outside of this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously".
If the timeout occurs, the returned Promise rejects with the specified reason.
If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
If the `rejectReason` parameter is a function and the timeout does not occur, the function will not be called.
Note: The rejection of the `operation` parameter is not handled by this function. You may want to handle it outside this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously."

@@ -707,9 +746,9 @@ ###### Type parameters

| :------ | :------ | :------ |
| `operation` | `Promise`<`T`\> \| () => `Promise`<`T`\> | The original Promise or a function that returns a Promise for which the timeout will be applied. |
| `operation` | `Promise`\<`T`\> \| () => `Promise`\<`T`\> | The original Promise or a function that returns a Promise to which the timeout will be applied. |
| `ms` | `number` | The number of milliseconds for the timeout. |
| `rejectReason` | `R` \| `PromiseLike`<`R`\> \| () => `R` \| `PromiseLike`<`R`\> | The reason to reject with if the timeout occurs, or a function that supplies the reason. |
| `rejectReason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> | The reason to reject with if the timeout occurs, or a function that supplies the reason. |
###### Returns
`Promise`<`T`\>
`Promise`\<`T`\>

@@ -722,9 +761,10 @@ A new Promise that rejects with the specified reason if the timeout occurs.

▸ `Static` **timeoutResolve**<`T`\>(`operation`, `ms`, `result?`): `Promise`<`T`\>
▸ `Static` **timeoutResolve**\<`T`\>(`operation`, `ms`, `result?`): `Promise`\<`T`\>
Applies a timeout to a Promise or a function that returns a Promise.
If the timeout occurs, resolves to the specified result.
If the timeout doesn't occur, the resolved result or rejection reason of the original Promise will be the outcome of the Promise returned from this function.
If the 'result' parameter is a function and timeout doesn't occur, the function won't be called.
The rejection of the 'operation' parameter is not handled by this function, you may want to handle it outside of this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously".
If the timeout occurs, the returned Promise resolves to the specified result.
If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
If the `result` parameter is a function and the timeout does not occur, the function will not be called.
Note: The rejection of the `operation` parameter is not handled by this function.
You may want to handle it outside this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously."

@@ -741,9 +781,9 @@ ###### Type parameters

| :------ | :------ | :------ |
| `operation` | `Promise`<`T`\> \| () => `Promise`<`T`\> | The original Promise or a function that returns a Promise for which the timeout will be applied. |
| `operation` | `Promise`\<`T`\> \| () => `Promise`\<`T`\> | The original Promise or a function that returns a Promise to which the timeout will be applied. |
| `ms` | `number` | The number of milliseconds for the timeout. |
| `result?` | `T` \| `PromiseLike`<`T`\> \| () => `T` \| `PromiseLike`<`T`\> | The result to be resolved with if the timeout occurs, or a function that supplies the result. |
| `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> | The result to resolve with if the timeout occurs, or a function that supplies the result. |
###### Returns
`Promise`<`T`\>
`Promise`\<`T`\>

@@ -754,7 +794,51 @@ A new Promise that resolves to the specified result if the timeout occurs.

##### withConcurrency
▸ `Static` **withConcurrency**\<`Data`, `Result`\>(`concurrency`, `jobs`, `operation`): `Promise`\<`Result`[]\>
Executes multiple jobs/operations with a specified level of concurrency.
Unlike `inParallel(...)`, this function may throw or reject an error when a job/operation fails.
When an error is re-thrown, remaining operations will not be executed.
If you want all the operations to always be executed, use [inParallel](#inparallel) instead.
###### Type parameters
| Name | Description |
| :------ | :------ |
| `Data` | The type of the job data, typically an Array. |
| `Result` | The type of the return value from the operation function. |
###### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `concurrency` | `number` | The number of jobs/operations to run concurrently. |
| `jobs` | `Iterable`\<`Data`\> | The job data to be processed. This function can handle an infinite or unknown number of elements safely. |
| `operation` | (`job`: `Data`, `index`: `number`) => `Promise`\<`Result`\> | The function that processes job data asynchronously. |
###### Returns
`Promise`\<`Result`[]\>
A promise that resolves to an array containing the results from the operation function.
The results in the returned array are in the same order as the corresponding elements in the jobs array.
**`Example`**
```ts
// At any time, there would be no more than 5 concurrency API calls. Error would be re-thrown immediately when it occurs.
const attributes = await PromiseUtils.withConcurrency(5, topicArns, async (topicArn) => {
const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;
return topicAttributes;
});
```
___
##### withRetry
▸ `Static` **withRetry**<`Result`, `TError`\>(`operation`, `backoff`, `shouldRetry?`): `Promise`<`Result`\>
▸ `Static` **withRetry**\<`Result`, `TError`\>(`operation`, `backoff`, `shouldRetry?`): `Promise`\<`Result`\>
Do an operation repeatedly until a criteria is met.
Repeatedly performs an operation until a specified criteria is met.

@@ -765,4 +849,4 @@ ###### Type parameters

| :------ | :------ | :------ |
| `Result` | `Result` | type of the operation result |
| `TError` | `any` | type of the possible error that could be generated by the operation |
| `Result` | `Result` | Type of the operation result. |
| `TError` | `any` | Type of the possible error that could be generated by the operation. |

@@ -773,11 +857,11 @@ ###### Parameters

| :------ | :------ | :------ |
| `operation` | (`attempt`: `number`, `previousResult`: `undefined` \| `Result`, `previousError`: `undefined` \| `TError`) => `Promise`<`Result`\> | a function that outputs a Promise result, normally the operation does not use its arguments |
| `backoff` | `number`[] \| (`attempt`: `number`, `previousResult`: `undefined` \| `Result`, `previousError`: `undefined` \| `TError`) => `undefined` \| `number` | Array of retry backoff periods (unit: milliseconds) or function for calculating them. If retry is desired, before making next call to the operation the desired backoff period would be waited. If the array runs out of elements or the function returns `undefined` or either the array or the function returns a negative number, there would be no further call to the operation. The `attempt` argument passed into backoff function starts from 1 because the function is called right after the first attempt and before the first retry. |
| `shouldRetry` | (`previousError`: `undefined` \| `TError`, `previousResult`: `undefined` \| `Result`, `attempt`: `number`) => `boolean` | Predicate function for deciding whether another call to the operation should happen. If this argument is not defined, retry would happen whenever the operation rejects with an error. `shouldRetry` would be evaluated before `backoff`. The `attempt` argument passed into shouldRetry function starts from 1. |
| `operation` | (`attempt`: `number`, `previousResult`: `undefined` \| `Result`, `previousError`: `undefined` \| `TError`) => `Promise`\<`Result`\> | A function that outputs a Promise result. Typically, the operation does not use its arguments. |
| `backoff` | `number`[] \| (`attempt`: `number`, `previousResult`: `undefined` \| `Result`, `previousError`: `undefined` \| `TError`) => `undefined` \| `number` | An array of retry backoff periods (in milliseconds) or a function for calculating them. If retry is desired, the specified backoff period is waited before the next call to the operation. If the array runs out of elements or the function returns `undefined` or a negative number, no further calls to the operation will be made. The `attempt` argument passed to the backoff function starts from 1, as it is called immediately after the first attempt and before the first retry. |
| `shouldRetry` | (`previousError`: `undefined` \| `TError`, `previousResult`: `undefined` \| `Result`, `attempt`: `number`) => `boolean` | A predicate function for deciding whether another call to the operation should occur. If this argument is not defined, a retry will occur whenever the operation rejects with an error. The `shouldRetry` function is evaluated before the `backoff`. The `attempt` argument passed to the shouldRetry function starts from 1. |
###### Returns
`Promise`<`Result`\>
`Promise`\<`Result`\>
Promise of the operation result potentially with retries already applied
A promise of the operation result, potentially with retries applied.

@@ -784,0 +868,0 @@ **`Example`**

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc