@handy-common-utils/promise-utils 1.4.1 → 1.6.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.
- package/README.md +216 -132
- package/dist/promise-utils.d.ts +122 -86
- package/dist/promise-utils.d.ts.map +1 -1
- package/dist/promise-utils.js +121 -83
- package/package.json +2 -2
package/dist/promise-utils.js
CHANGED
|
@@ -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
|
-
*
|
|
40
|
-
* This function is useful for client
|
|
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
|
|
52
|
-
* @template Collection type of the returned
|
|
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
|
|
55
|
-
* @param nextParameter
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
* @param collect
|
|
60
|
-
* @param initialCollection initial collection which
|
|
61
|
-
* @param initialParameter
|
|
62
|
-
* @returns
|
|
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
|
-
*
|
|
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
|
|
88
|
-
* @template TError
|
|
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
|
|
91
|
-
* @param backoff
|
|
92
|
-
* If retry is desired,
|
|
93
|
-
* If the array runs out of elements or the function returns `undefined` or
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
* `
|
|
99
|
-
*
|
|
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,18 +117,46 @@ class PromiseUtils {
|
|
|
118
117
|
return finalOutcome.result;
|
|
119
118
|
}
|
|
120
119
|
/**
|
|
121
|
-
*
|
|
120
|
+
* Executes multiple jobs/operations with a specified level of concurrency.
|
|
122
121
|
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
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
|
-
*
|
|
128
|
-
*
|
|
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, { abortOnError: true });
|
|
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
158
|
* // Capture errors in the returned array
|
|
132
|
-
* const attributesAndPossibleErrors = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
|
|
159
|
+
* const attributesAndPossibleErrors: Array<JobResult|JobError> = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
|
|
133
160
|
* const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;
|
|
134
161
|
* return topicAttributes;
|
|
135
162
|
* });
|
|
@@ -142,17 +169,18 @@ class PromiseUtils {
|
|
|
142
169
|
* // handle the error
|
|
143
170
|
* }
|
|
144
171
|
*
|
|
145
|
-
* @template Data
|
|
146
|
-
* @template Result
|
|
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`.
|
|
147
175
|
*
|
|
148
|
-
* @param parallelism
|
|
149
|
-
* @param jobs
|
|
150
|
-
*
|
|
151
|
-
* @param
|
|
152
|
-
* @param options
|
|
153
|
-
* @returns
|
|
154
|
-
*
|
|
155
|
-
*
|
|
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.
|
|
156
184
|
*/
|
|
157
185
|
static async inParallel(parallelism, jobs, operation, options) {
|
|
158
186
|
if (parallelism < 1) {
|
|
@@ -178,21 +206,23 @@ class PromiseUtils {
|
|
|
178
206
|
return jobResults;
|
|
179
207
|
}
|
|
180
208
|
/**
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
* @param
|
|
184
|
-
* @
|
|
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.
|
|
185
214
|
*/
|
|
186
215
|
static delayedResolve(ms, result) {
|
|
187
216
|
// eslint-disable-next-line no-promise-executor-return
|
|
188
217
|
return new Promise(resolve => setTimeout(() => resolve(typeof result === 'function' ? result() : result), ms));
|
|
189
218
|
}
|
|
190
219
|
/**
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
* @param
|
|
194
|
-
*
|
|
195
|
-
*
|
|
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.
|
|
196
226
|
*/
|
|
197
227
|
static delayedReject(ms, reason) {
|
|
198
228
|
// eslint-disable-next-line no-promise-executor-return
|
|
@@ -203,15 +233,16 @@ class PromiseUtils {
|
|
|
203
233
|
}
|
|
204
234
|
/**
|
|
205
235
|
* Applies a timeout to a Promise or a function that returns a Promise.
|
|
206
|
-
* If the timeout occurs, resolves to the specified result.
|
|
207
|
-
* If the timeout
|
|
208
|
-
* If the
|
|
209
|
-
* The rejection of the
|
|
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."
|
|
210
241
|
*
|
|
211
|
-
* @param operation The original Promise or a function that returns a Promise
|
|
242
|
+
* @param operation The original Promise or a function that returns a Promise to which the timeout will be applied.
|
|
212
243
|
* @param ms The number of milliseconds for the timeout.
|
|
213
|
-
* @param result The result to
|
|
214
|
-
* @
|
|
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.
|
|
215
246
|
*/
|
|
216
247
|
static timeoutResolve(operation, ms, result) {
|
|
217
248
|
const promise = typeof operation === 'function' ? operation() : operation;
|
|
@@ -225,15 +256,15 @@ class PromiseUtils {
|
|
|
225
256
|
}
|
|
226
257
|
/**
|
|
227
258
|
* Applies a timeout to a Promise or a function that returns a Promise.
|
|
228
|
-
* If the timeout occurs, rejects with the specified reason.
|
|
229
|
-
* If the timeout
|
|
230
|
-
* If the
|
|
231
|
-
* The rejection of the
|
|
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."
|
|
232
263
|
*
|
|
233
|
-
* @param operation The original Promise or a function that returns a Promise
|
|
264
|
+
* @param operation The original Promise or a function that returns a Promise to which the timeout will be applied.
|
|
234
265
|
* @param ms The number of milliseconds for the timeout.
|
|
235
266
|
* @param rejectReason The reason to reject with if the timeout occurs, or a function that supplies the reason.
|
|
236
|
-
* @
|
|
267
|
+
* @returns A new Promise that rejects with the specified reason if the timeout occurs.
|
|
237
268
|
*/
|
|
238
269
|
static timeoutReject(operation, ms, rejectReason) {
|
|
239
270
|
const promise = typeof operation === 'function' ? operation() : operation;
|
|
@@ -246,10 +277,11 @@ class PromiseUtils {
|
|
|
246
277
|
]);
|
|
247
278
|
}
|
|
248
279
|
/**
|
|
249
|
-
*
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
* @
|
|
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.
|
|
253
285
|
*/
|
|
254
286
|
static promiseState(p) {
|
|
255
287
|
const t = {};
|
|
@@ -257,14 +289,16 @@ class PromiseUtils {
|
|
|
257
289
|
.then(v => (v === t) ? PromiseState.Pending : PromiseState.Fulfilled, () => PromiseState.Rejected);
|
|
258
290
|
}
|
|
259
291
|
/**
|
|
260
|
-
*
|
|
261
|
-
*
|
|
262
|
-
* The operation function has access to the state (when `synchronized` is called),
|
|
263
|
-
*
|
|
264
|
-
*
|
|
265
|
-
*
|
|
266
|
-
*
|
|
267
|
-
* @
|
|
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.
|
|
268
302
|
*/
|
|
269
303
|
static async synchronized(lock, operation) {
|
|
270
304
|
let resultPromise;
|
|
@@ -293,9 +327,9 @@ class PromiseUtils {
|
|
|
293
327
|
}
|
|
294
328
|
/**
|
|
295
329
|
* This is just another spelling of {@link PromiseUtils.synchronized}.
|
|
296
|
-
* @param lock
|
|
297
|
-
* @param operation
|
|
298
|
-
* @returns
|
|
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.
|
|
299
333
|
*/
|
|
300
334
|
static async synchronised(lock, operation) {
|
|
301
335
|
return PromiseUtils.synchronized(lock, operation);
|
|
@@ -311,6 +345,10 @@ exports.repeat = PromiseUtils.repeat;
|
|
|
311
345
|
* See {@link PromiseUtils.withRetry} for full documentation.
|
|
312
346
|
*/
|
|
313
347
|
exports.withRetry = PromiseUtils.withRetry;
|
|
348
|
+
/**
|
|
349
|
+
* See {@link PromiseUtils.withConcurrency} for full documentation.
|
|
350
|
+
*/
|
|
351
|
+
exports.withConcurrency = PromiseUtils.withConcurrency;
|
|
314
352
|
/**
|
|
315
353
|
* See {@link PromiseUtils.inParallel} for full documentation.
|
|
316
354
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@handy-common-utils/promise-utils",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.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.
|
|
19
|
+
"@handy-common-utils/dev-dependencies-mocha": "^1.5.4",
|
|
20
20
|
"@types/node": "^18.17.1"
|
|
21
21
|
},
|
|
22
22
|
"publishConfig": {
|