@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.
- package/README.md +228 -137
- package/dist/promise-utils.d.ts +124 -86
- package/dist/promise-utils.d.ts.map +1 -1
- package/dist/promise-utils.js +123 -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,21 +117,51 @@ 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);
|
|
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
|
|
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
|
|
144
|
-
* @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`.
|
|
145
175
|
*
|
|
146
|
-
* @param parallelism
|
|
147
|
-
* @param jobs
|
|
148
|
-
*
|
|
149
|
-
* @param
|
|
150
|
-
* @param options
|
|
151
|
-
* @returns
|
|
152
|
-
*
|
|
153
|
-
*
|
|
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
|
-
*
|
|
180
|
-
*
|
|
181
|
-
* @param
|
|
182
|
-
* @
|
|
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
|
-
*
|
|
190
|
-
*
|
|
191
|
-
* @param
|
|
192
|
-
*
|
|
193
|
-
*
|
|
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
|
|
206
|
-
* If the
|
|
207
|
-
* 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."
|
|
208
241
|
*
|
|
209
|
-
* @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.
|
|
210
243
|
* @param ms The number of milliseconds for the timeout.
|
|
211
|
-
* @param result The result to
|
|
212
|
-
* @
|
|
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
|
|
228
|
-
* If the
|
|
229
|
-
* 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."
|
|
230
263
|
*
|
|
231
|
-
* @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.
|
|
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
|
-
* @
|
|
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
|
-
*
|
|
248
|
-
*
|
|
249
|
-
*
|
|
250
|
-
* @
|
|
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
|
-
*
|
|
259
|
-
*
|
|
260
|
-
* The operation function has access to the state (when `synchronized` is called),
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
*
|
|
265
|
-
* @
|
|
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
|
|
295
|
-
* @param operation
|
|
296
|
-
* @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.
|
|
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.
|
|
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.
|
|
19
|
+
"@handy-common-utils/dev-dependencies-mocha": "^1.5.4",
|
|
20
20
|
"@types/node": "^18.17.1"
|
|
21
21
|
},
|
|
22
22
|
"publishConfig": {
|