@handy-common-utils/promise-utils 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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;
3
+ 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;
4
4
  /**
5
5
  * Array of 25 Fibonacci numbers starting from 1 up to 317811.
6
6
  * It can be used to form your own backoff interval array.
@@ -36,8 +36,8 @@ var PromiseState;
36
36
  })(PromiseState || (exports.PromiseState = PromiseState = {}));
37
37
  class PromiseUtils {
38
38
  /**
39
- * Do an operation repeatedly and collect all the results.
40
- * This function is useful for client side pagination.
39
+ * Executes an operation repeatedly and collects all the results.
40
+ * This function is very useful for many scenarios, such like client-side pagination.
41
41
  *
42
42
  * @example
43
43
  * const domainNameObjects = await PromiseUtils.repeat(
@@ -47,19 +47,19 @@ class PromiseUtils {
47
47
  * [] as APIGateway.DomainName[],
48
48
  * );
49
49
  *
50
- * @template Result type of the operation result
51
- * @template Param type of the input to the operation, normally the input is a paging parameter
52
- * @template Collection type of the returned value of this function
50
+ * @template Result The type of the operation result.
51
+ * @template Param The type of the input to the operation, typically a paging parameter.
52
+ * @template Collection The type of the collection returned by this function.
53
53
  *
54
- * @param operation a function that takes paging parameter as input and outputs a result, normally the operation supports paging
55
- * @param nextParameter The function for calculating next parameter from the operation result.
56
- * Normally the parameter controls paging,
57
- * This function should return null when next invocation of the operation function is not desired.
58
- * If next invocation is desired, the return value of this function can be a Promise or not a Promise.
59
- * @param collect the function for merging operation result into the collection
60
- * @param initialCollection initial collection which would be the first argument passed into the first invocation of the collect function
61
- * @param initialParameter the parameter for the first operation
62
- * @returns Promise of collection of all the results returned by the operation function
54
+ * @param operation A function that takes a parameter as input and returns a result. Typically, the parameter has optional fields to control paging.
55
+ * @param nextParameter A function for calculating the next parameter from the operation result.
56
+ * Normally, this parameter controls paging.
57
+ * This function should return null when no further invocation of the operation function is desired.
58
+ * If further invocation is desired, the return value of this function can be a Promise or a non-Promise value.
59
+ * @param collect A function for merging the operation result into the collection.
60
+ * @param initialCollection The initial collection, which will be the first argument passed to the first invocation of the collect function.
61
+ * @param initialParameter The parameter for the first operation.
62
+ * @returns A promise that resolves to a collection of all the results returned by the operation function.
63
63
  *
64
64
  */
65
65
  static async repeat(operation, nextParameter, collect, initialCollection, initialParameter = {}) {
@@ -77,27 +77,26 @@ class PromiseUtils {
77
77
  return collection;
78
78
  }
79
79
  /**
80
- * Do an operation repeatedly until a criteria is met.
80
+ * Repeatedly performs an operation until a specified criteria is met.
81
81
  *
82
82
  * @example
83
83
  * const result = await PromiseUtils.withRetry(() => doSomething(), [100, 200, 300, 500, 800, 1000]);
84
84
  * const result2 = await PromiseUtils.withRetry(() => doSomething(), Array.from({length: 10}, (_v, i) => 1000 * Math.min(FIBONACCI_SEQUENCE[i], 10), err => err.statusCode === 429);
85
85
  * const result3 = await PromiseUtils.withRetry(() => doSomething(), attempt => attempt <= 8 ? 1000 * Math.min(FIBONACCI_SEQUENCE[attempt - 1], 10) : undefined, err => err.statusCode === 429);
86
86
  *
87
- * @template Result type of the operation result
88
- * @template TError type of the possible error that could be generated by the operation
87
+ * @template Result Type of the operation result.
88
+ * @template TError Type of the possible error that could be generated by the operation.
89
89
  *
90
- * @param operation a function that outputs a Promise result, normally the operation does not use its arguments
91
- * @param backoff Array of retry backoff periods (unit: milliseconds) or function for calculating them.
92
- * If retry is desired, before making next call to the operation the desired backoff period would be waited.
93
- * If the array runs out of elements or the function returns `undefined` or either the array or the function returns a negative number,
94
- * there would be no further call to the operation.
95
- * 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.
96
- * @param shouldRetry Predicate function for deciding whether another call to the operation should happen.
97
- * If this argument is not defined, retry would happen whenever the operation rejects with an error.
98
- * `shouldRetry` would be evaluated before `backoff`.
99
- * The `attempt` argument passed into shouldRetry function starts from 1.
100
- * @returns Promise of the operation result potentially with retries already applied
90
+ * @param operation A function that outputs a Promise result. Typically, the operation does not use its arguments.
91
+ * @param backoff An array of retry backoff periods (in milliseconds) or a function for calculating them.
92
+ * If retry is desired, the specified backoff period is waited before the next call to the operation.
93
+ * 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.
94
+ * 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.
95
+ * @param shouldRetry A predicate function for deciding whether another call to the operation should occur.
96
+ * If this argument is not defined, a retry will occur whenever the operation rejects with an error.
97
+ * The `shouldRetry` function is evaluated before the `backoff`.
98
+ * The `attempt` argument passed to the shouldRetry function starts from 1.
99
+ * @returns A promise of the operation result, potentially with retries applied.
101
100
  */
102
101
  static async withRetry(operation, backoff, shouldRetry = (previousError, _previousResult, _attempt) => previousError !== undefined) {
103
102
  let attempt = 1;
@@ -118,21 +117,51 @@ class PromiseUtils {
118
117
  return finalOutcome.result;
119
118
  }
120
119
  /**
121
- * Run multiple jobs/operations in parallel.
120
+ * Executes multiple jobs/operations with a specified level of concurrency.
122
121
  *
123
- * By default this function does not throw / reject with error when any of the job/operation fails.
124
- * Operation errors are returned together with operation results in the same returned array.
125
- * That also means this function only returns when all the jobs/operations settle (either resolve or reject).
122
+ * Unlike `inParallel(...)`, this function may throw or reject an error when a job/operation fails.
123
+ * When an error is re-thrown, remaining operations will not be executed.
124
+ * If you want all the operations to always be executed, use {@link PromiseUtils.inParallel} instead.
126
125
  *
127
- * However, if options.abortOnError is true, this function throws / rejects with error when any of the job/operation fails.
128
- * That also means, some of the jobs/operations may not get the chance to be executed if one of them fails.
126
+ * @example
127
+ * // At any time, there would be no more than 5 concurrency API calls. Error would be re-thrown immediately when it occurs.
128
+ * const attributes = await PromiseUtils.withConcurrency(5, topicArns, async (topicArn) => {
129
+ * const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;
130
+ * return topicAttributes;
131
+ * });
132
+ *
133
+ *
134
+ * @template Data The type of the job data, typically an Array.
135
+ * @template Result The type of the return value from the operation function.
136
+ *
137
+ * @param concurrency The number of jobs/operations to run concurrently.
138
+ * @param jobs The job data to be processed. This function can handle an infinite or unknown number of elements safely.
139
+ * @param operation The function that processes job data asynchronously.
140
+ * @returns A promise that resolves to an array containing the results from the operation function.
141
+ * The results in the returned array are in the same order as the corresponding elements in the jobs array.
142
+ */
143
+ static async withConcurrency(concurrency, jobs, operation) {
144
+ return (0, exports.inParallel)(concurrency, jobs, operation);
145
+ }
146
+ /**
147
+ * Executes multiple jobs/operations in parallel. By default, all operations are executed regardless of any failures.
148
+ * In most cases, using {@link PromiseUtils.withConcurrency} might be more convenient.
149
+ *
150
+ * By default, this function does not throw or reject an error when any job/operation fails.
151
+ * Errors from operations are returned alongside results in the returned array.
152
+ * This function only resolves when all jobs/operations are settled (either resolved or rejected).
153
+ *
154
+ * If `options.abortOnError` is set to true, this function throws (or rejects with) an error immediately when any job/operation fails.
155
+ * In this mode, some jobs/operations may not be executed if one fails.
129
156
  *
130
157
  * @example
131
- * const attributesAndPossibleErrors = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
158
+ * // Capture errors in the returned array
159
+ * const attributesAndPossibleErrors: Array<JobResult|JobError> = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
132
160
  * const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;
133
161
  * return topicAttributes;
134
162
  * });
135
163
  *
164
+ * // Abort on the first error
136
165
  * let results: Array<JobResult>;
137
166
  * try {
138
167
  * results = await PromiseUtils.inParallel(100, jobs, async (job) => processor.process(job), { abortOnError: true });
@@ -140,17 +169,18 @@ class PromiseUtils {
140
169
  * // handle the error
141
170
  * }
142
171
  *
143
- * @template Data Type of the job data, usually it would be an Array
144
- * @template Result Type of the return value of the operation function
172
+ * @template Data The type of the job data, typically an Array.
173
+ * @template Result The type of the return value from the operation function.
174
+ * @template TError The type for the error that could be thrown from the operation function, defaults to `Result`.
145
175
  *
146
- * @param parallelism how many jobs/operations can be running at the same time
147
- * @param jobs job data which will be the input to operation function.
148
- * This function is safe when there are infinite unknown number of elements in the job data.
149
- * @param operation the function that turns job data into result asynchronously
150
- * @param options Options for controlling the behavior of this function.
151
- * @returns Promise of void if the operation function does not return a value,
152
- * or promise of an array containing outcomes from the operation function.
153
- * In the returned array containing outcomes, each element is either the fulfilled result, or the rejected error/reason.
176
+ * @param parallelism The number of jobs/operations to run concurrently.
177
+ * @param jobs The job data to be processed. This function can safely handle an infinite or unknown number of elements.
178
+ * @param operation The function that processes job data asynchronously.
179
+ * @param options Options to control the function's behavior.
180
+ * @param options.abortOnError If true, the function aborts and throws an error on the first failed operation.
181
+ * @returns A promise that resolves to an array containing the results of the operations.
182
+ * Each element is either a fulfilled result or a rejected error/reason.
183
+ * The results or errors in the returned array are in the same order as the corresponding elements in the jobs array.
154
184
  */
155
185
  static async inParallel(parallelism, jobs, operation, options) {
156
186
  if (parallelism < 1) {
@@ -176,21 +206,23 @@ class PromiseUtils {
176
206
  return jobResults;
177
207
  }
178
208
  /**
179
- * Create a Promise that resolves after number of milliseconds specified
180
- * @param ms number of milliseconds after which the created Promise would resolve
181
- * @param result the result to be resolved for the Promise, or a function that supplies the result.
182
- * @returns the new Promise created
209
+ * Creates a Promise that resolves after a specified number of milliseconds.
210
+ *
211
+ * @param ms The number of milliseconds after which the created Promise will resolve.
212
+ * @param result The result to be resolved by the Promise, or a function that supplies the result.
213
+ * @returns A new Promise that resolves with the specified result after the specified delay.
183
214
  */
184
215
  static delayedResolve(ms, result) {
185
216
  // eslint-disable-next-line no-promise-executor-return
186
217
  return new Promise(resolve => setTimeout(() => resolve(typeof result === 'function' ? result() : result), ms));
187
218
  }
188
219
  /**
189
- * Create a Promise that rejects after number of milliseconds specified.
190
- * @param ms number of milliseconds after which the created Promise would reject
191
- * @param reason the reason of the rejection for the Promise, or a function that supplies the reason.
192
- * 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.
193
- * @returns the new Promise created
220
+ * Creates a Promise that rejects after a specified number of milliseconds.
221
+ *
222
+ * @param ms The number of milliseconds after which the created Promise will reject.
223
+ * @param reason The reason for the rejection, or a function that supplies the reason.
224
+ * If the reason is a rejected Promise, the outcome of it will be the rejection reason of the returned Promise.
225
+ * @returns A new Promise that rejects with the specified reason after the specified delay.
194
226
  */
195
227
  static delayedReject(ms, reason) {
196
228
  // eslint-disable-next-line no-promise-executor-return
@@ -201,15 +233,16 @@ class PromiseUtils {
201
233
  }
202
234
  /**
203
235
  * Applies a timeout to a Promise or a function that returns a Promise.
204
- * If the timeout occurs, resolves to the specified result.
205
- * 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.
206
- * If the 'result' parameter is a function and timeout doesn't occur, the function won't be called.
207
- * 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".
236
+ * If the timeout occurs, the returned Promise resolves to the specified result.
237
+ * If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
238
+ * If the `result` parameter is a function and the timeout does not occur, the function will not be called.
239
+ * Note: The rejection of the `operation` parameter is not handled by this function.
240
+ * You may want to handle it outside this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously."
208
241
  *
209
- * @param operation The original Promise or a function that returns a Promise for which the timeout will be applied.
242
+ * @param operation The original Promise or a function that returns a Promise to which the timeout will be applied.
210
243
  * @param ms The number of milliseconds for the timeout.
211
- * @param result The result to be resolved with if the timeout occurs, or a function that supplies the result.
212
- * @return A new Promise that resolves to the specified result if the timeout occurs.
244
+ * @param result The result to resolve with if the timeout occurs, or a function that supplies the result.
245
+ * @returns A new Promise that resolves to the specified result if the timeout occurs.
213
246
  */
214
247
  static timeoutResolve(operation, ms, result) {
215
248
  const promise = typeof operation === 'function' ? operation() : operation;
@@ -223,15 +256,15 @@ class PromiseUtils {
223
256
  }
224
257
  /**
225
258
  * Applies a timeout to a Promise or a function that returns a Promise.
226
- * If the timeout occurs, rejects with the specified reason.
227
- * 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.
228
- * If the 'reason' parameter is a function and timeout doesn't occur, the function won't be called.
229
- * 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".
259
+ * If the timeout occurs, the returned Promise rejects with the specified reason.
260
+ * If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
261
+ * If the `rejectReason` parameter is a function and the timeout does not occur, the function will not be called.
262
+ * 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."
230
263
  *
231
- * @param operation The original Promise or a function that returns a Promise for which the timeout will be applied.
264
+ * @param operation The original Promise or a function that returns a Promise to which the timeout will be applied.
232
265
  * @param ms The number of milliseconds for the timeout.
233
266
  * @param rejectReason The reason to reject with if the timeout occurs, or a function that supplies the reason.
234
- * @return A new Promise that rejects with the specified reason if the timeout occurs.
267
+ * @returns A new Promise that rejects with the specified reason if the timeout occurs.
235
268
  */
236
269
  static timeoutReject(operation, ms, rejectReason) {
237
270
  const promise = typeof operation === 'function' ? operation() : operation;
@@ -244,10 +277,11 @@ class PromiseUtils {
244
277
  ]);
245
278
  }
246
279
  /**
247
- * Get the state of the Promise.
248
- * Please note that the returned value is a Promise, although it resolves immediately.
249
- * @param p the Promise for which we would like to know its state
250
- * @return A Promise that resolves immediately containing the state of the input Promise
280
+ * Retrieves the state of the specified Promise.
281
+ * Note: The returned value is a Promise that resolves immediately.
282
+ *
283
+ * @param p The Promise whose state is to be determined.
284
+ * @returns A Promise that resolves immediately with the state of the input Promise.
251
285
  */
252
286
  static promiseState(p) {
253
287
  const t = {};
@@ -255,14 +289,16 @@ class PromiseUtils {
255
289
  .then(v => (v === t) ? PromiseState.Pending : PromiseState.Fulfilled, () => PromiseState.Rejected);
256
290
  }
257
291
  /**
258
- * Equivalent of `synchronized` in Java.
259
- * In any situation there's no concurrent execution of any operation function associated with the same lock.
260
- * The operation function has access to the state (when `synchronized` is called), settledState (when the operation function is called),
261
- * and result (could be the fulfilled result or the rejected reason) of the previous operation.
262
- * In case there is no previous invocation, state, settledState and result would all be undefined.
263
- * @param lock the object (could be a string, a number, or `this` in a class) that is used to apply the lock
264
- * @param operation function for doing the computation and returning a Promise
265
- * @returns the result of the operation function
292
+ * Provides mutual exclusion similar to `synchronized` in Java.
293
+ * Ensures no concurrent execution of any operation function associated with the same lock.
294
+ * The operation function has access to the state (when `synchronized` is called),
295
+ * settledState (when the operation function is called),
296
+ * and result (either the fulfilled result or the rejected reason) of the previous operation.
297
+ * If there is no previous invocation, state, settledState, and result will all be undefined.
298
+ *
299
+ * @param lock The object (such as a string, a number, or `this` in a class) used to identify the lock.
300
+ * @param operation The function that performs the computation and returns a Promise.
301
+ * @returns The result of the operation function.
266
302
  */
267
303
  static async synchronized(lock, operation) {
268
304
  let resultPromise;
@@ -291,9 +327,9 @@ class PromiseUtils {
291
327
  }
292
328
  /**
293
329
  * This is just another spelling of {@link PromiseUtils.synchronized}.
294
- * @param lock the object (could be a string, a number, or `this` in a class) that is used to apply the lock
295
- * @param operation function for doing the computation and returning a Promise
296
- * @returns the result of the operation function
330
+ * @param lock The object (such as a string, a number, or `this` in a class) used to identify the lock.
331
+ * @param operation The function that performs the computation and returns a Promise.
332
+ * @returns The result of the operation function.
297
333
  */
298
334
  static async synchronised(lock, operation) {
299
335
  return PromiseUtils.synchronized(lock, operation);
@@ -309,6 +345,10 @@ exports.repeat = PromiseUtils.repeat;
309
345
  * See {@link PromiseUtils.withRetry} for full documentation.
310
346
  */
311
347
  exports.withRetry = PromiseUtils.withRetry;
348
+ /**
349
+ * See {@link PromiseUtils.withConcurrency} for full documentation.
350
+ */
351
+ exports.withConcurrency = PromiseUtils.withConcurrency;
312
352
  /**
313
353
  * See {@link PromiseUtils.inParallel} for full documentation.
314
354
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@handy-common-utils/promise-utils",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Promise related utilities",
5
5
  "scripts": {
6
6
  "pretest": "eslint . --ext .ts",
@@ -16,7 +16,7 @@
16
16
  "types": "dist/promise-utils.d.ts",
17
17
  "bin": {},
18
18
  "devDependencies": {
19
- "@handy-common-utils/dev-dependencies-mocha": "^1.3.1",
19
+ "@handy-common-utils/dev-dependencies-mocha": "^1.5.4",
20
20
  "@types/node": "^18.17.1"
21
21
  },
22
22
  "publishConfig": {