@handy-common-utils/promise-utils 1.6.0 → 1.7.1

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 CHANGED
@@ -3,16 +3,19 @@
3
3
  These Promise-related utilities boast 100% test coverage, ensuring robust reliability.
4
4
  The package, free of external dependencies, offers essential functions such as:
5
5
 
6
- - `repeat`: Executes an operation repeatedly, very useful to collect all results through pagination.
7
- - `withRetry`: Retries an operation until a specified condition is met.
8
- - `withConcurrency`: Executes multiple operations with specified level of concurrency, and abort remaining operations when an error happens.
9
- - `inParallel`: Executes multiple operations with specified level of concurrency, all operations are guaranteed to be executed regardless of any possible error.
6
+ - `repeat`: Executes an operation repeatedly; useful for collecting paged results.
7
+ - `withRetry`: Retries an operation with configurable backoff and retry predicate.
8
+ - `withConcurrency`: Runs jobs in parallel with a concurrency limit and aborts remaining jobs on the first error.
9
+ - `inParallel`: Runs jobs in parallel with a concurrency limit and returns all results and errors (does not abort on any error by default).
10
10
  - `delayedResolve`: Creates a Promise that resolves after a specified delay.
11
11
  - `delayedReject`: Creates a Promise that rejects after a specified delay.
12
- - `timeoutResolve`: Applies a timeout to a Promise and resolves with a specified result if the timeout occurs.
13
- - `timeoutReject`: Applies a timeout to a Promise and rejects with a specified error/reason if the timeout occurs.
14
- - `promiseState`: Retrieves the state of a Promise.
15
- - `synchronized`: Provides mutual exclusion for concurrent operations using a lock mechanism, similar to `synchronized` in Java.
12
+ - `cancellableDelayedResolve`: Like `delayedResolve` but returns `{ stop(), promise }` to allow cancelling before the timer fires.
13
+ - `cancellableDelayedReject`: Like `delayedReject` but returns `{ stop(), promise }` to allow cancelling before the timer fires.
14
+ - `timeoutResolve`: Applies a timeout to a Promise and resolves with a fallback value if the timeout occurs.
15
+ - `timeoutReject`: Applies a timeout to a Promise and rejects with a fallback reason if the timeout occurs.
16
+ - `promiseState`: Retrieves the state of a Promise (Pending/Fulfilled/Rejected).
17
+ - `synchronized` / `synchronised`: Provides mutual exclusion (lock) semantics for async operations.
18
+ - `runPeriodically`: Runs an operation periodically with configurable intervals and stopping conditions.
16
19
 
17
20
  [![Version](https://img.shields.io/npm/v/@handy-common-utils/promise-utils.svg)](https://npmjs.org/package/@handy-common-utils/promise-utils)
18
21
  [![Downloads/week](https://img.shields.io/npm/dw/@handy-common-utils/promise-utils.svg)](https://npmjs.org/package/@handy-common-utils/promise-utils)
@@ -27,465 +30,292 @@ First add it as a dependency:
27
30
  npm install @handy-common-utils/promise-utils
28
31
  ```
29
32
 
30
- Then you can use it in the code:
33
+ Then you can use it in the code. Below are minimal examples; full short snippets are grouped in the "Examples" section further down.
31
34
 
32
35
  ```javascript
33
36
  import { PromiseUtils } from '@handy-common-utils/promise-utils';
34
37
 
35
- // delayedResolve(...), delayedReject(...), promiseState(...)
36
- const p1 = PromiseUtils.delayedResolve(50, 1);
37
- const p2 = PromiseUtils.delayedReject(50, 2);
38
- await expect(PromiseUtils.promiseState(p1)).eventually.eq(PromiseState.Pending);
39
- await expect(PromiseUtils.promiseState(p2)).eventually.eq(PromiseState.Pending);
40
- await PromiseUtils.delayedResolve(80);
41
- await expect(PromiseUtils.promiseState(p1)).eventually.eq(PromiseState.Fulfilled);
42
- await expect(PromiseUtils.promiseState(p2)).eventually.eq(PromiseState.Rejected);
43
-
44
- // timeoutReject(...)
45
- const p = PromiseUtils.timeoutReject(PromiseUtils.delayedReject(80, '1'), 10, '2');
46
- await expect(p).to.be.rejectedWith('2');
47
-
48
- // repeat(...)
49
- async repeatFetchingItemsByPosition<T>(
50
- fetchItemsByPosition: (parameter: { position?: string }) => Promise<{ position?: string; items?: Array<T> }>,
51
- ) {
52
- return PromiseUtils.repeat(
53
- fetchItemsByPosition,
54
- response => response.position ? { position: response.position } : null,
55
- (collection, response) => response.items ? collection.concat(response.items) : collection,
56
- [] as Array<T>,
57
- );
58
- }
38
+ // basic usage (short):
39
+ await PromiseUtils.delayedResolve(50, 'ok');
40
+ await PromiseUtils.timeoutReject(PromiseUtils.delayedReject(80, '1'), 10, '2');
41
+
42
+ // See the Examples section below for more grouped snippets (Timers, Concurrency, Scheduling).
59
43
  ```
60
44
 
61
- You can either import and use the [PromiseUtils class](#classespromiseutilsmd) as shown above,
62
- or you can import its re-exported functions directly like below:
45
+ You can either import and use the [PromiseUtils class](#classespromiseutilsmd) as shown above, or import only the helpers you need. For example:
63
46
 
64
47
  ```javascript
65
- import { withRetry, inParallel, FIBONACCI_SEQUENCE, EXPONENTIAL_SEQUENCE } from '@handy-common-utils/promise-utils';
66
-
67
- // withRetry(...)
68
- const result = await withRetry(() => doSomething(), [100, 200, 300, 500, 800, 1000]);
69
- const result2 = await withRetry(() => doSomething(), Array.from({length: 10}, (_v, i) => 1000 * Math.min(FIBONACCI_SEQUENCE[i], 10)), err => err.statusCode === 429);
70
- const result3 = await withRetry(() => doSomething(), attempt => attempt <= 8 ? 1000 * Math.min(EXPONENTIAL_SEQUENCE[attempt - 1], 10) : undefined, err => err.statusCode === 429);
71
- statusCode === 429);
72
-
73
- // Capture errors in the returned array
74
- const attributesAndPossibleErrors = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
75
- const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;
76
- return topicAttributes;
77
- });
78
-
79
- // Abort on the first error
80
- let results: Array<JobResult>;
81
- try {
82
- results = await PromiseUtils.withConcurrency(100, jobs, async (job) => processor.process(job));
83
- } catch (error) {
84
- // handle the error
85
- }
48
+ import { withRetry, delayedResolve, cancellableDelayedReject, withConcurrency, inParallel, runPeriodically } from '@handy-common-utils/promise-utils';
86
49
 
50
+ // Import-focused example — the actual usage is the same as using PromiseUtils.
51
+ const result = await withRetry(() => doSomething(), [100, 200, 300]);
52
+ const p = delayedResolve(100, 'ok');
53
+ const c = cancellableDelayedReject(2000, 'timeout-reason');
54
+ // c.stop() can cancel the scheduled rejection before it fires
87
55
  ```
88
56
 
89
- # API
90
-
91
- <!-- API start -->
92
- <a name="readmemd"></a>
93
-
94
- ## @handy-common-utils/promise-utils
95
-
96
- ### Enumerations
97
-
98
- - [PromiseState](#enumspromisestatemd)
99
-
100
- ### Classes
101
-
102
- - [PromiseUtils](#classespromiseutilsmd)
103
-
104
- ### Variables
57
+ ## Quick examples
105
58
 
106
- #### EXPONENTIAL\_SEQUENCE
107
-
108
- • `Const` **EXPONENTIAL\_SEQUENCE**: `number`[]
109
-
110
- Array of 25 exponential numbers starting from 1 up to 33554432.
111
- It can be used to form your own backoff interval array.
59
+ ### Timers
112
60
 
113
- **`Example`**
61
+ ```javascript
62
+ // delayedResolve / delayedReject
63
+ await delayedResolve(50, 'ok');
114
64
 
115
- ```ts
116
- // 1ms, 2ms, 4ms, 8ms, 16ms, 32ms
117
- PromiseUtils.withRetry(() => doSomething(), EXPONENTIAL_SEQUENCE.slice(0, 5), err => err.statusCode === 429);
118
- // 1s, 2s, 4s, 8s, 10s, 10s, 10s, 10s, 10s, 10s
119
- PromiseUtils.withRetry(() => doSomething(), Array.from({length: 10}, (_v, i) => 1000 * Math.min(EXPONENTIAL_SEQUENCE[i], 10)), err => err.statusCode === 429);
120
- // with +-10% randomness: 1s, 2s, 4s, 8s
121
- PromiseUtils.withRetry(() => doSomething(), FIBONACCI_SEQUENCE.slice(0, 4).map(n => 1000 * n * (1 + (Math.random() - 0.5) / 5)), err => err.statusCode === 429);
65
+ // cancellableDelayedResolve: returns { stop, promise }
66
+ const { stop, promise } = cancellableDelayedResolve(1000, () => Promise.resolve('ready'));
67
+ // cancel before it fires
68
+ stop();
122
69
  ```
123
70
 
124
- ___
71
+ `delayedReject` and `cancellableDelayedReject` are similar.
125
72
 
126
- #### FIBONACCI\_SEQUENCE
73
+ ### Concurrency & Parallelism
127
74
 
128
- • `Const` **FIBONACCI\_SEQUENCE**: `number`[]
129
-
130
- Array of 25 Fibonacci numbers starting from 1 up to 317811.
131
- It can be used to form your own backoff interval array.
132
-
133
- **`Example`**
75
+ ```javascript
76
+ // withConcurrency: abort remaining on first error
77
+ try {
78
+ await withConcurrency(5, jobs, async (job) => process(job));
79
+ } catch (err) {
80
+ // an error occurred and remaining jobs may not have been started
81
+ }
134
82
 
135
- ```ts
136
- // 1ms, 2ms, 3ms, 5ms, 8ms, 13ms
137
- PromiseUtils.withRetry(() => doSomething(), FIBONACCI_SEQUENCE.slice(0, 5), err => err.statusCode === 429);
138
- // 1s, 2s, 3s, 4s, 8s, 10s, 10s, 10s, 10s, 10s
139
- PromiseUtils.withRetry(() => doSomething(), Array.from({length: 10}, (_v, i) => 1000 * Math.min(FIBONACCI_SEQUENCE[i], 10)), err => err.statusCode === 429);
140
- // with +-10% randomness: 1s, 2s, 3s, 5s, 8s, 13s
141
- PromiseUtils.withRetry(() => doSomething(), FIBONACCI_SEQUENCE.slice(0, 5).map(n => 1000 * n * (1 + (Math.random() - 0.5) / 5)), err => err.statusCode === 429);
83
+ // inParallel: collect all results and errors
84
+ const results = await inParallel(5, jobs, async (job) => process(job));
85
+ // results contains either values or error objects in the original order
142
86
  ```
143
87
 
144
- ### Functions
145
-
146
- #### delayedReject
147
-
148
- ▸ **delayedReject**\<`T`, `R`\>(`ms`, `reason`): `Promise`\<`T`\>
149
-
150
- See [delayedReject](#delayedreject) for full documentation.
151
-
152
- ##### Type parameters
153
-
154
- | Name | Type |
155
- | :------ | :------ |
156
- | `T` | `never` |
157
- | `R` | `any` |
158
-
159
- ##### Parameters
160
-
161
- | Name | Type |
162
- | :------ | :------ |
163
- | `ms` | `number` |
164
- | `reason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> |
165
-
166
- ##### Returns
167
-
168
- `Promise`\<`T`\>
169
-
170
- ___
171
-
172
- #### delayedResolve
173
-
174
- ▸ **delayedResolve**\<`T`\>(`ms`, `result?`): `Promise`\<`T`\>
175
-
176
- See [delayedResolve](#delayedresolve) for full documentation.
177
-
178
- ##### Type parameters
179
-
180
- | Name |
181
- | :------ |
182
- | `T` |
183
-
184
- ##### Parameters
185
-
186
- | Name | Type |
187
- | :------ | :------ |
188
- | `ms` | `number` |
189
- | `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> |
190
-
191
- ##### Returns
192
-
193
- `Promise`\<`T`\>
194
-
195
- ___
196
-
197
- #### inParallel
198
-
199
- ▸ **inParallel**\<`Data`, `Result`, `TError`\>(`parallelism`, `jobs`, `operation`, `options?`): `Promise`\<(`Result` \| `TError`)[]\>
200
-
201
- See [inParallel](#inparallel) for full documentation.
202
-
203
- ##### Type parameters
204
-
205
- | Name | Type |
206
- | :------ | :------ |
207
- | `Data` | `Data` |
208
- | `Result` | `Result` |
209
- | `TError` | `Result` |
210
-
211
- ##### Parameters
212
-
213
- | Name | Type |
214
- | :------ | :------ |
215
- | `parallelism` | `number` |
216
- | `jobs` | `Iterable`\<`Data`\> |
217
- | `operation` | (`job`: `Data`, `index`: `number`) => `Promise`\<`Result`\> |
218
- | `options?` | `Object` |
219
- | `options.abortOnError` | `boolean` |
220
-
221
- ##### Returns
222
-
223
- `Promise`\<(`Result` \| `TError`)[]\>
224
-
225
- ___
226
-
227
- #### promiseState
88
+ ### Scheduling & Utilities
228
89
 
229
- ▸ **promiseState**(`p`): `Promise`\<[`PromiseState`](#enumspromisestatemd)\>
230
-
231
- See [promiseState](#promisestate) for full documentation.
232
-
233
- ##### Parameters
234
-
235
- | Name | Type |
236
- | :------ | :------ |
237
- | `p` | `Promise`\<`any`\> |
238
-
239
- ##### Returns
240
-
241
- `Promise`\<[`PromiseState`](#enumspromisestatemd)\>
242
-
243
- ___
244
-
245
- #### repeat
246
-
247
- ▸ **repeat**\<`Result`, `Param`, `Collection`\>(`operation`, `nextParameter`, `collect`, `initialCollection`, `initialParameter?`): `Promise`\<`Collection`\>
248
-
249
- See [repeat](#repeat) for full documentation.
250
-
251
- ##### Type parameters
252
-
253
- | Name |
254
- | :------ |
255
- | `Result` |
256
- | `Param` |
257
- | `Collection` |
258
-
259
- ##### Parameters
260
-
261
- | Name | Type |
262
- | :------ | :------ |
263
- | `operation` | (`parameter`: `Partial`\<`Param`\>) => `Promise`\<`Result`\> |
264
- | `nextParameter` | (`response`: `Result`) => ``null`` \| `Partial`\<`Param`\> \| `Promise`\<`Partial`\<`Param`\>\> |
265
- | `collect` | (`collection`: `Collection`, `result`: `Result`) => `Collection` |
266
- | `initialCollection` | `Collection` |
267
- | `initialParameter` | `Partial`\<`Param`\> |
90
+ ```javascript
91
+ // runPeriodically: schedule repeated work
92
+ const controller = runPeriodically(async (i) => {
93
+ console.log('iteration', i);
94
+ await delayedResolve(10);
95
+ }, 100, { maxExecutions: 5 });
96
+ ...
97
+ controller.stop(); // stop now
98
+ await controller.done; // wait until it stops
99
+
100
+ // synchronized: lock a resource
101
+ await PromiseUtils.synchronized('my-lock', async () => {
102
+ // only one callback for 'my-lock' runs at a time
103
+ });
104
+ ```
268
105
 
269
- ##### Returns
106
+ # API
270
107
 
271
- `Promise`\<`Collection`\>
108
+ <!-- API start -->
109
+ <a name="readmemd"></a>
272
110
 
273
- ___
111
+ ## @handy-common-utils/promise-utils
274
112
 
275
- #### synchronised
113
+ ### Classes
276
114
 
277
- **synchronised**\<`T`\>(`lock`, `operation`): `Promise`\<`T`\>
115
+ | Class | Description |
116
+ | ------ | ------ |
117
+ | [PromiseUtils](#classespromiseutilsmd) | - |
278
118
 
279
- See [synchronised](#synchronised) for full documentation.
119
+ ### Type Aliases
280
120
 
281
- ##### Type parameters
121
+ | Type Alias | Description |
122
+ | ------ | ------ |
123
+ | [PromiseStateType](#type-aliasespromisestatetypemd) | - |
282
124
 
283
- | Name |
284
- | :------ |
285
- | `T` |
125
+ ### Variables
286
126
 
287
- ##### Parameters
127
+ | Variable | Description |
128
+ | ------ | ------ |
129
+ | [cancellableDelayedReject](#variablescancellabledelayedrejectmd) | Creates a cancellable timer that will reject after a specified number of milliseconds. |
130
+ | [cancellableDelayedResolve](#variablescancellabledelayedresolvemd) | Creates a cancellable timer that will resolve after a specified number of milliseconds. |
131
+ | [delayedReject](#variablesdelayedrejectmd) | Creates a Promise that rejects after a specified number of milliseconds. |
132
+ | [delayedResolve](#variablesdelayedresolvemd) | Creates a Promise that resolves after a specified number of milliseconds. |
133
+ | [EXPONENTIAL\_SEQUENCE](#variablesexponential_sequencemd) | Array of 25 exponential numbers starting from 1 up to 33554432. It can be used to form your own backoff interval array. |
134
+ | [FIBONACCI\_SEQUENCE](#variablesfibonacci_sequencemd) | Array of 25 Fibonacci numbers starting from 1 up to 317811. It can be used to form your own backoff interval array. |
135
+ | [inParallel](#variablesinparallelmd) | Executes multiple jobs/operations in parallel. By default, all operations are executed regardless of any failures. In most cases, using withConcurrency might be more convenient. |
136
+ | [promiseState](#variablespromisestatemd) | Retrieves the state of the specified Promise. Note: The returned value is a Promise that resolves immediately. |
137
+ | [PromiseState](#variablespromisestate-1md) | The state of a Promise can only be one of: Pending, Fulfilled, and Rejected. |
138
+ | [repeat](#variablesrepeatmd) | Executes an operation repeatedly and collects all the results. This function is very useful for many scenarios, such like client-side pagination. |
139
+ | [runPeriodically](#variablesrunperiodicallymd) | Runs an operation periodically with configurable intervals and stopping conditions. |
140
+ | [synchronised](#variablessynchronisedmd) | This is just another spelling of synchronized. |
141
+ | [synchronized](#variablessynchronizedmd) | 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. |
142
+ | [timeoutReject](#variablestimeoutrejectmd) | Applies a timeout to a Promise or a function that returns a Promise. 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." |
143
+ | [timeoutResolve](#variablestimeoutresolvemd) | Applies a timeout to a Promise or a function that returns a Promise. 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." |
144
+ | [withConcurrency](#variableswithconcurrencymd) | Executes multiple jobs/operations with a specified level of concurrency. |
145
+ | [withRetry](#variableswithretrymd) | Repeatedly performs an operation until a specified criteria is met. |
288
146
 
289
- | Name | Type |
290
- | :------ | :------ |
291
- | `lock` | `any` |
292
- | `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`\<`T`\> |
147
+ ## Classes
293
148
 
294
- ##### Returns
295
149
 
296
- `Promise`\<`T`\>
150
+ <a id="classespromiseutilsmd"></a>
297
151
 
298
- ___
152
+ ### Abstract Class: PromiseUtils
299
153
 
300
- #### synchronized
154
+ #### Constructors
301
155
 
302
- **synchronized**\<`T`\>(`lock`, `operation`): `Promise`\<`T`\>
156
+ <a id="api-constructor"></a>
303
157
 
304
- See [synchronized](#synchronized) for full documentation.
158
+ ##### Constructor
305
159
 
306
- ##### Type parameters
160
+ > **new PromiseUtils**(): `PromiseUtils`
307
161
 
308
- | Name |
309
- | :------ |
310
- | `T` |
162
+ ###### Returns
311
163
 
312
- ##### Parameters
164
+ `PromiseUtils`
313
165
 
314
- | Name | Type |
315
- | :------ | :------ |
316
- | `lock` | `any` |
317
- | `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`\<`T`\> |
166
+ #### Methods
318
167
 
319
- ##### Returns
168
+ <a id="api-cancellabledelayedreject"></a>
320
169
 
321
- `Promise`\<`T`\>
170
+ ##### cancellableDelayedReject()
322
171
 
323
- ___
172
+ > `static` **cancellableDelayedReject**\<`T`, `R`\>(`ms`, `reason`): `object`
324
173
 
325
- #### timeoutReject
174
+ Creates a cancellable timer that will reject after a specified number of milliseconds.
326
175
 
327
- **timeoutReject**\<`T`, `R`\>(`operation`, `ms`, `rejectReason`): `Promise`\<`T`\>
176
+ The returned object contains:
177
+ - `stop()` to cancel the scheduled rejection (if called before the timer fires). Calling
178
+ `stop()` prevents the promise from being settled by this timer.
179
+ - `promise` which will reject with the supplied `reason` (or the value returned by the
180
+ `reason` function) after `ms` milliseconds unless `stop()` is called first.
328
181
 
329
- See [timeoutReject](#timeoutreject) for full documentation.
182
+ If the `reason` is a PromiseLike that rejects, its rejection value will be used as the rejection reason.
330
183
 
331
- ##### Type parameters
184
+ ###### Type Parameters
332
185
 
333
- | Name | Type |
334
- | :------ | :------ |
186
+ | Type Parameter | Default type |
187
+ | ------ | ------ |
335
188
  | `T` | `never` |
336
189
  | `R` | `any` |
337
190
 
338
- ##### Parameters
339
-
340
- | Name | Type |
341
- | :------ | :------ |
342
- | `operation` | `Promise`\<`T`\> \| () => `Promise`\<`T`\> |
343
- | `ms` | `number` |
344
- | `rejectReason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> |
345
-
346
- ##### Returns
347
-
348
- `Promise`\<`T`\>
349
-
350
- ___
351
-
352
- #### timeoutResolve
353
-
354
- ▸ **timeoutResolve**\<`T`\>(`operation`, `ms`, `result?`): `Promise`\<`T`\>
191
+ ###### Parameters
355
192
 
356
- See [timeoutResolve](#timeoutresolve) for full documentation.
193
+ | Parameter | Type | Description |
194
+ | ------ | ------ | ------ |
195
+ | `ms` | `number` | The number of milliseconds after which the scheduled rejection will occur. |
196
+ | `reason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> | The reason for the rejection, or a function that supplies the reason. |
357
197
 
358
- ##### Type parameters
198
+ ###### Returns
359
199
 
360
- | Name |
361
- | :------ |
362
- | `T` |
200
+ `object`
363
201
 
364
- ##### Parameters
202
+ An object with `stop()` and `promise`.
365
203
 
366
204
  | Name | Type |
367
- | :------ | :------ |
368
- | `operation` | `Promise`\<`T`\> \| () => `Promise`\<`T`\> |
369
- | `ms` | `number` |
370
- | `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> |
371
-
372
- ##### Returns
205
+ | ------ | ------ |
206
+ | `promise` | `Promise`\<`T`\> |
207
+ | `stop()` | () => `void` |
373
208
 
374
- `Promise`\<`T`\>
375
-
376
- ___
377
-
378
- #### withConcurrency
379
-
380
- ▸ **withConcurrency**\<`Data`, `Result`\>(`concurrency`, `jobs`, `operation`): `Promise`\<`Result`[]\>
209
+ ***
381
210
 
382
- See [withConcurrency](#withconcurrency) for full documentation.
211
+ <a id="api-cancellabledelayedresolve"></a>
383
212
 
384
- ##### Type parameters
213
+ ##### cancellableDelayedResolve()
385
214
 
386
- | Name |
387
- | :------ |
388
- | `Data` |
389
- | `Result` |
215
+ > `static` **cancellableDelayedResolve**\<`T`\>(`ms`, `result?`): `object`
390
216
 
391
- ##### Parameters
217
+ Creates a cancellable timer that will resolve after a specified number of milliseconds.
392
218
 
393
- | Name | Type |
394
- | :------ | :------ |
395
- | `concurrency` | `number` |
396
- | `jobs` | `Iterable`\<`Data`\> |
397
- | `operation` | (`job`: `Data`, `index`: `number`) => `Promise`\<`Result`\> |
398
-
399
- ##### Returns
219
+ The returned object contains:
220
+ - `stop()` to cancel the scheduled resolution (if called before the timer fires). Calling
221
+ `stop()` prevents the promise from being settled by this timer.
222
+ - `promise` which will resolve with the supplied `result` (or the value returned by the
223
+ `result` function) after `ms` milliseconds unless `stop()` is called first.
400
224
 
401
- `Promise`\<`Result`[]\>
225
+ Note: If the `result` is a function that returns a Promise, the returned `promise` will
226
+ resolve with that Promise's resolution (i.e. it behaves like resolving with a PromiseLike).
402
227
 
403
- ___
228
+ ###### Type Parameters
404
229
 
405
- #### withRetry
230
+ | Type Parameter |
231
+ | ------ |
232
+ | `T` |
406
233
 
407
- **withRetry**\<`Result`, `TError`\>(`operation`, `backoff`, `shouldRetry?`): `Promise`\<`Result`\>
234
+ ###### Parameters
408
235
 
409
- See [withRetry](#withretry) for full documentation.
236
+ | Parameter | Type | Description |
237
+ | ------ | ------ | ------ |
238
+ | `ms` | `number` | The number of milliseconds after which the scheduled resolution will occur. |
239
+ | `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> | The result to be resolved by the Promise, or a function that supplies the result. |
410
240
 
411
- ##### Type parameters
241
+ ###### Returns
412
242
 
413
- | Name | Type |
414
- | :------ | :------ |
415
- | `Result` | `Result` |
416
- | `TError` | `any` |
243
+ `object`
417
244
 
418
- ##### Parameters
245
+ An object with `stop()` and `promise`.
419
246
 
420
247
  | Name | Type |
421
- | :------ | :------ |
422
- | `operation` | (`attempt`: `number`, `previousResult`: `undefined` \| `Result`, `previousError`: `undefined` \| `TError`) => `Promise`\<`Result`\> |
423
- | `backoff` | `number`[] \| (`attempt`: `number`, `previousResult`: `undefined` \| `Result`, `previousError`: `undefined` \| `TError`) => `undefined` \| `number` |
424
- | `shouldRetry` | (`previousError`: `undefined` \| `TError`, `previousResult`: `undefined` \| `Result`, `attempt`: `number`) => `boolean` |
425
-
426
- ##### Returns
427
-
428
- `Promise`\<`Result`\>
429
-
430
- ## Classes
431
-
432
-
433
- <a name="classespromiseutilsmd"></a>
434
-
435
- ### Class: PromiseUtils
248
+ | ------ | ------ |
249
+ | `promise` | `Promise`\<`T`\> |
250
+ | `stop()` | () => `void` |
436
251
 
437
- #### Constructors
252
+ ***
438
253
 
439
- ##### constructor
254
+ <a id="api-delayedreject"></a>
440
255
 
441
- **new PromiseUtils**()
256
+ ##### delayedReject()
442
257
 
443
- #### Methods
258
+ > `static` **delayedReject**\<`T`, `R`\>(`ms`, `reason`): `Promise`\<`T`\>
444
259
 
445
- ##### delayedReject
260
+ Creates a Promise that rejects after a specified number of milliseconds.
446
261
 
447
- `Static` **delayedReject**\<`T`, `R`\>(`ms`, `reason`): `Promise`\<`T`\>
262
+ The `reason` argument may be:
263
+ - a value to reject with,
264
+ - a PromiseLike whose rejection will be adopted by the returned Promise, or
265
+ - a function which is invoked when the timer fires and may return a value or a PromiseLike.
448
266
 
449
- Creates a Promise that rejects after a specified number of milliseconds.
267
+ If `reason` is a function, it is called when the timer elapses; if it returns a Promise,
268
+ the returned Promise will reject with that Promise's rejection reason (or reject with the
269
+ returned value if it resolves).
450
270
 
451
- ###### Type parameters
271
+ ###### Type Parameters
452
272
 
453
- | Name | Type |
454
- | :------ | :------ |
273
+ | Type Parameter | Default type |
274
+ | ------ | ------ |
455
275
  | `T` | `never` |
456
276
  | `R` | `any` |
457
277
 
458
278
  ###### Parameters
459
279
 
460
- | Name | Type | Description |
461
- | :------ | :------ | :------ |
280
+ | Parameter | Type | Description |
281
+ | ------ | ------ | ------ |
462
282
  | `ms` | `number` | The number of milliseconds after which the created Promise will reject. |
463
- | `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. |
283
+ | `reason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> | The reason for the rejection, or a function that supplies the reason. |
464
284
 
465
285
  ###### Returns
466
286
 
467
287
  `Promise`\<`T`\>
468
288
 
469
- A new Promise that rejects with the specified reason after the specified delay.
289
+ A Promise that rejects with the specified reason after the specified delay.
290
+
291
+ ***
470
292
 
471
- ___
293
+ <a id="api-delayedresolve"></a>
472
294
 
473
- ##### delayedResolve
295
+ ##### delayedResolve()
474
296
 
475
- `Static` **delayedResolve**\<`T`\>(`ms`, `result?`): `Promise`\<`T`\>
297
+ > `static` **delayedResolve**\<`T`\>(`ms`, `result?`): `Promise`\<`T`\>
476
298
 
477
299
  Creates a Promise that resolves after a specified number of milliseconds.
478
300
 
479
- ###### Type parameters
301
+ The `result` argument may be:
302
+ - a value to resolve with,
303
+ - a PromiseLike whose resolution will be adopted by the returned Promise, or
304
+ - a function which is invoked when the timer fires and may return a value or a PromiseLike.
305
+
306
+ If `result` is a function, it is called when the timer elapses; if it returns a Promise,
307
+ the returned Promise will adopt that Promise's outcome.
308
+
309
+ ###### Type Parameters
480
310
 
481
- | Name |
482
- | :------ |
311
+ | Type Parameter |
312
+ | ------ |
483
313
  | `T` |
484
314
 
485
315
  ###### Parameters
486
316
 
487
- | Name | Type | Description |
488
- | :------ | :------ | :------ |
317
+ | Parameter | Type | Description |
318
+ | ------ | ------ | ------ |
489
319
  | `ms` | `number` | The number of milliseconds after which the created Promise will resolve. |
490
320
  | `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> | The result to be resolved by the Promise, or a function that supplies the result. |
491
321
 
@@ -493,16 +323,18 @@ Creates a Promise that resolves after a specified number of milliseconds.
493
323
 
494
324
  `Promise`\<`T`\>
495
325
 
496
- A new Promise that resolves with the specified result after the specified delay.
326
+ A Promise that resolves with the specified result after the specified delay.
497
327
 
498
- ___
328
+ ***
499
329
 
500
- ##### inParallel
330
+ <a id="api-inparallel"></a>
501
331
 
502
- `Static` **inParallel**\<`Data`, `Result`, `TError`\>(`parallelism`, `jobs`, `operation`, `options?`): `Promise`\<(`Result` \| `TError`)[]\>
332
+ ##### inParallel()
333
+
334
+ > `static` **inParallel**\<`Data`, `Result`, `TError`\>(`parallelism`, `jobs`, `operation`, `options?`): `Promise`\<(`Result` \| `TError`)[]\>
503
335
 
504
336
  Executes multiple jobs/operations in parallel. By default, all operations are executed regardless of any failures.
505
- In most cases, using [withConcurrency](#withconcurrency) might be more convenient.
337
+ In most cases, using [PromiseUtils.withConcurrency](#api-withconcurrency) might be more convenient.
506
338
 
507
339
  By default, this function does not throw or reject an error when any job/operation fails.
508
340
  Errors from operations are returned alongside results in the returned array.
@@ -511,23 +343,23 @@ This function only resolves when all jobs/operations are settled (either resolve
511
343
  If `options.abortOnError` is set to true, this function throws (or rejects with) an error immediately when any job/operation fails.
512
344
  In this mode, some jobs/operations may not be executed if one fails.
513
345
 
514
- ###### Type parameters
346
+ ###### Type Parameters
515
347
 
516
- | Name | Type | Description |
517
- | :------ | :------ | :------ |
518
- | `Data` | `Data` | The type of the job data, typically an Array. |
519
- | `Result` | `Result` | The type of the return value from the operation function. |
348
+ | Type Parameter | Default type | Description |
349
+ | ------ | ------ | ------ |
350
+ | `Data` | - | The type of the job data, typically an Array. |
351
+ | `Result` | - | The type of the return value from the operation function. |
520
352
  | `TError` | `Result` | The type for the error that could be thrown from the operation function, defaults to `Result`. |
521
353
 
522
354
  ###### Parameters
523
355
 
524
- | Name | Type | Description |
525
- | :------ | :------ | :------ |
356
+ | Parameter | Type | Description |
357
+ | ------ | ------ | ------ |
526
358
  | `parallelism` | `number` | The number of jobs/operations to run concurrently. |
527
359
  | `jobs` | `Iterable`\<`Data`\> | The job data to be processed. This function can safely handle an infinite or unknown number of elements. |
528
- | `operation` | (`job`: `Data`, `index`: `number`) => `Promise`\<`Result`\> | The function that processes job data asynchronously. |
529
- | `options?` | `Object` | Options to control the function's behavior. |
530
- | `options.abortOnError` | `boolean` | If true, the function aborts and throws an error on the first failed operation. |
360
+ | `operation` | (`job`, `index`) => `Promise`\<`Result`\> | The function that processes job data asynchronously. |
361
+ | `options?` | \{ `abortOnError`: `boolean`; \} | Options to control the function's behavior. |
362
+ | `options.abortOnError?` | `boolean` | If true, the function aborts and throws an error on the first failed operation. |
531
363
 
532
364
  ###### Returns
533
365
 
@@ -537,7 +369,7 @@ A promise that resolves to an array containing the results of the operations.
537
369
  Each element is either a fulfilled result or a rejected error/reason.
538
370
  The results or errors in the returned array are in the same order as the corresponding elements in the jobs array.
539
371
 
540
- **`Example`**
372
+ ###### Example
541
373
 
542
374
  ```ts
543
375
  // Capture errors in the returned array
@@ -555,51 +387,55 @@ try {
555
387
  }
556
388
  ```
557
389
 
558
- ___
390
+ ***
391
+
392
+ <a id="api-promisestate"></a>
559
393
 
560
- ##### promiseState
394
+ ##### promiseState()
561
395
 
562
- `Static` **promiseState**(`p`): `Promise`\<[`PromiseState`](#enumspromisestatemd)\>
396
+ > `static` **promiseState**(`p`): `Promise`\<`"Pending"` \| `"Fulfilled"` \| `"Rejected"`\>
563
397
 
564
398
  Retrieves the state of the specified Promise.
565
399
  Note: The returned value is a Promise that resolves immediately.
566
400
 
567
401
  ###### Parameters
568
402
 
569
- | Name | Type | Description |
570
- | :------ | :------ | :------ |
403
+ | Parameter | Type | Description |
404
+ | ------ | ------ | ------ |
571
405
  | `p` | `Promise`\<`any`\> | The Promise whose state is to be determined. |
572
406
 
573
407
  ###### Returns
574
408
 
575
- `Promise`\<[`PromiseState`](#enumspromisestatemd)\>
409
+ `Promise`\<`"Pending"` \| `"Fulfilled"` \| `"Rejected"`\>
576
410
 
577
411
  A Promise that resolves immediately with the state of the input Promise.
578
412
 
579
- ___
413
+ ***
580
414
 
581
- ##### repeat
415
+ <a id="api-repeat"></a>
582
416
 
583
- `Static` **repeat**\<`Result`, `Param`, `Collection`\>(`operation`, `nextParameter`, `collect`, `initialCollection`, `initialParameter?`): `Promise`\<`Collection`\>
417
+ ##### repeat()
418
+
419
+ > `static` **repeat**\<`Result`, `Param`, `Collection`\>(`operation`, `nextParameter`, `collect`, `initialCollection`, `initialParameter`): `Promise`\<`Collection`\>
584
420
 
585
421
  Executes an operation repeatedly and collects all the results.
586
422
  This function is very useful for many scenarios, such like client-side pagination.
587
423
 
588
- ###### Type parameters
424
+ ###### Type Parameters
589
425
 
590
- | Name | Description |
591
- | :------ | :------ |
426
+ | Type Parameter | Description |
427
+ | ------ | ------ |
592
428
  | `Result` | The type of the operation result. |
593
429
  | `Param` | The type of the input to the operation, typically a paging parameter. |
594
430
  | `Collection` | The type of the collection returned by this function. |
595
431
 
596
432
  ###### Parameters
597
433
 
598
- | Name | Type | Description |
599
- | :------ | :------ | :------ |
600
- | `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. |
601
- | `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. |
602
- | `collect` | (`collection`: `Collection`, `result`: `Result`) => `Collection` | A function for merging the operation result into the collection. |
434
+ | Parameter | Type | Description |
435
+ | ------ | ------ | ------ |
436
+ | `operation` | (`parameter`) => `Promise`\<`Result`\> | A function that takes a parameter as input and returns a result. Typically, the parameter has optional fields to control paging. |
437
+ | `nextParameter` | (`response`) => `Partial`\<`Param`\> \| `Promise`\<`Partial`\<`Param`\>\> \| `null` | 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. |
438
+ | `collect` | (`collection`, `result`) => `Collection` | A function for merging the operation result into the collection. |
603
439
  | `initialCollection` | `Collection` | The initial collection, which will be the first argument passed to the first invocation of the collect function. |
604
440
  | `initialParameter` | `Partial`\<`Param`\> | The parameter for the first operation. |
605
441
 
@@ -609,7 +445,7 @@ This function is very useful for many scenarios, such like client-side paginatio
609
445
 
610
446
  A promise that resolves to a collection of all the results returned by the operation function.
611
447
 
612
- **`Example`**
448
+ ###### Example
613
449
 
614
450
  ```ts
615
451
  const domainNameObjects = await PromiseUtils.repeat(
@@ -620,26 +456,91 @@ const domainNameObjects = await PromiseUtils.repeat(
620
456
  );
621
457
  ```
622
458
 
623
- ___
459
+ ***
460
+
461
+ <a id="api-runperiodically"></a>
462
+
463
+ ##### runPeriodically()
464
+
465
+ > `static` **runPeriodically**\<`T`\>(`operation`, `interval`, `options?`): `object`
466
+
467
+ Runs an operation periodically with configurable intervals and stopping conditions.
468
+
469
+ - `interval` may be a single number (ms), an array of numbers, or a function
470
+ that receives the iteration number (starting at 1) and returns the next
471
+ interval in milliseconds or `undefined` to stop.
472
+ - If the interval array runs out of elements or the function returns `undefined`
473
+ (or a negative value), no further invocations will be scheduled.
474
+
475
+ Options:
476
+ - `maxExecutions` stop after N runs (inclusive).
477
+ - `maxDurationMs` stop after elapsed ms since the first scheduled start.
478
+ - `schedule` controls how the interval is measured:
479
+ - `'delayAfterEnd'`: wait the interval after the previous operation completes
480
+ before scheduling the next one (equivalent to a fixed delay between ends).
481
+ - `'delayBetweenStarts'`: keep start times on a regular schedule (interval measured
482
+ between the starts of successive operations).
483
+ The default schedule is `'delayBetweenStarts'`.
484
+
485
+ Returns an object with `stop()` to cancel further executions and `done` which
486
+ resolves when the periodic runner stops. If the provided `operation` throws or
487
+ rejects, the `done` promise will reject with that error so callers can handle it.
488
+
489
+ Note: The first invocation of `operation` is scheduled after the first interval
490
+ elapses (i.e. this function does NOT call `operation` immediately). If you need
491
+ an immediate run, invoke `operation(1)` yourself before calling `runPeriodically`.
492
+
493
+ ###### Type Parameters
494
+
495
+ | Type Parameter | Description |
496
+ | ------ | ------ |
497
+ | `T` | The operation return type (ignored by the runner; used for typing). |
498
+
499
+ ###### Parameters
500
+
501
+ | Parameter | Type | Description |
502
+ | ------ | ------ | ------ |
503
+ | `operation` | (`iteration`) => `T` \| `Promise`\<`T`\> | Function to run each iteration. Receives the iteration index (1-based). |
504
+ | `interval` | `number` \| `number`[] \| (`iteration`) => `number` \| `undefined` | Number | number[] | ((iteration: number) => number|undefined) defining waits. |
505
+ | `options?` | \{ `maxDurationMs?`: `number`; `maxExecutions?`: `number`; `schedule?`: `"delayAfterEnd"` \| `"delayBetweenStarts"`; \} | Optional configuration. |
506
+ | `options.maxDurationMs?` | `number` | Stop after N milliseconds. |
507
+ | `options.maxExecutions?` | `number` | Stop after N executions. |
508
+ | `options.schedule?` | `"delayAfterEnd"` \| `"delayBetweenStarts"` | How to measure intervals: `'delayAfterEnd'` or `'delayBetweenStarts'`. |
509
+
510
+ ###### Returns
511
+
512
+ `object`
513
+
514
+ An object containing `stop()` to cancel further executions and `done` Promise
515
+ which resolves when the periodic runner stops (or rejects if the operation errors).
624
516
 
625
- ##### synchronised
517
+ | Name | Type |
518
+ | ------ | ------ |
519
+ | `done` | `Promise`\<`void`\> |
520
+ | `stop()` | () => `void` |
521
+
522
+ ***
523
+
524
+ <a id="api-synchronised"></a>
525
+
526
+ ##### synchronised()
626
527
 
627
- `Static` **synchronised**\<`T`\>(`lock`, `operation`): `Promise`\<`T`\>
528
+ > `static` **synchronised**\<`T`\>(`lock`, `operation`): `Promise`\<`T`\>
628
529
 
629
- This is just another spelling of [synchronized](#synchronized).
530
+ This is just another spelling of [PromiseUtils.synchronized](#api-synchronized).
630
531
 
631
- ###### Type parameters
532
+ ###### Type Parameters
632
533
 
633
- | Name |
634
- | :------ |
534
+ | Type Parameter |
535
+ | ------ |
635
536
  | `T` |
636
537
 
637
538
  ###### Parameters
638
539
 
639
- | Name | Type | Description |
640
- | :------ | :------ | :------ |
540
+ | Parameter | Type | Description |
541
+ | ------ | ------ | ------ |
641
542
  | `lock` | `any` | The object (such as a string, a number, or `this` in a class) used to identify the lock. |
642
- | `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`\<`T`\> | The function that performs the computation and returns a Promise. |
543
+ | `operation` | (`previousState`, `previousSettledState`, `previousResult`) => `Promise`\<`T`\> | The function that performs the computation and returns a Promise. |
643
544
 
644
545
  ###### Returns
645
546
 
@@ -647,11 +548,13 @@ This is just another spelling of [synchronized](#synchronized).
647
548
 
648
549
  The result of the operation function.
649
550
 
650
- ___
551
+ ***
651
552
 
652
- ##### synchronized
553
+ <a id="api-synchronized"></a>
653
554
 
654
- `Static` **synchronized**\<`T`\>(`lock`, `operation`): `Promise`\<`T`\>
555
+ ##### synchronized()
556
+
557
+ > `static` **synchronized**\<`T`\>(`lock`, `operation`): `Promise`\<`T`\>
655
558
 
656
559
  Provides mutual exclusion similar to `synchronized` in Java.
657
560
  Ensures no concurrent execution of any operation function associated with the same lock.
@@ -660,18 +563,18 @@ settledState (when the operation function is called),
660
563
  and result (either the fulfilled result or the rejected reason) of the previous operation.
661
564
  If there is no previous invocation, state, settledState, and result will all be undefined.
662
565
 
663
- ###### Type parameters
566
+ ###### Type Parameters
664
567
 
665
- | Name |
666
- | :------ |
568
+ | Type Parameter |
569
+ | ------ |
667
570
  | `T` |
668
571
 
669
572
  ###### Parameters
670
573
 
671
- | Name | Type | Description |
672
- | :------ | :------ | :------ |
574
+ | Parameter | Type | Description |
575
+ | ------ | ------ | ------ |
673
576
  | `lock` | `any` | The object (such as a string, a number, or `this` in a class) used to identify the lock. |
674
- | `operation` | (`previousState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousSettledState`: `undefined` \| [`PromiseState`](#enumspromisestatemd), `previousResult`: `any`) => `Promise`\<`T`\> | The function that performs the computation and returns a Promise. |
577
+ | `operation` | (`previousState`, `previousSettledState`, `previousResult`) => `Promise`\<`T`\> | The function that performs the computation and returns a Promise. |
675
578
 
676
579
  ###### Returns
677
580
 
@@ -679,11 +582,13 @@ If there is no previous invocation, state, settledState, and result will all be
679
582
 
680
583
  The result of the operation function.
681
584
 
682
- ___
585
+ ***
586
+
587
+ <a id="api-timeoutreject"></a>
683
588
 
684
- ##### timeoutReject
589
+ ##### timeoutReject()
685
590
 
686
- `Static` **timeoutReject**\<`T`, `R`\>(`operation`, `ms`, `rejectReason`): `Promise`\<`T`\>
591
+ > `static` **timeoutReject**\<`T`, `R`\>(`operation`, `ms`, `rejectReason`): `Promise`\<`T`\>
687
592
 
688
593
  Applies a timeout to a Promise or a function that returns a Promise.
689
594
  If the timeout occurs, the returned Promise rejects with the specified reason.
@@ -691,17 +596,17 @@ If the timeout does not occur, the returned Promise resolves or rejects based on
691
596
  If the `rejectReason` parameter is a function and the timeout does not occur, the function will not be called.
692
597
  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."
693
598
 
694
- ###### Type parameters
599
+ ###### Type Parameters
695
600
 
696
- | Name | Type |
697
- | :------ | :------ |
601
+ | Type Parameter | Default type |
602
+ | ------ | ------ |
698
603
  | `T` | `never` |
699
604
  | `R` | `any` |
700
605
 
701
606
  ###### Parameters
702
607
 
703
- | Name | Type | Description |
704
- | :------ | :------ | :------ |
608
+ | Parameter | Type | Description |
609
+ | ------ | ------ | ------ |
705
610
  | `operation` | `Promise`\<`T`\> \| () => `Promise`\<`T`\> | The original Promise or a function that returns a Promise to which the timeout will be applied. |
706
611
  | `ms` | `number` | The number of milliseconds for the timeout. |
707
612
  | `rejectReason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> | The reason to reject with if the timeout occurs, or a function that supplies the reason. |
@@ -712,11 +617,13 @@ Note: The rejection of the `operation` parameter is not handled by this function
712
617
 
713
618
  A new Promise that rejects with the specified reason if the timeout occurs.
714
619
 
715
- ___
620
+ ***
621
+
622
+ <a id="api-timeoutresolve"></a>
716
623
 
717
- ##### timeoutResolve
624
+ ##### timeoutResolve()
718
625
 
719
- `Static` **timeoutResolve**\<`T`\>(`operation`, `ms`, `result?`): `Promise`\<`T`\>
626
+ > `static` **timeoutResolve**\<`T`\>(`operation`, `ms`, `result?`): `Promise`\<`T`\>
720
627
 
721
628
  Applies a timeout to a Promise or a function that returns a Promise.
722
629
  If the timeout occurs, the returned Promise resolves to the specified result.
@@ -725,16 +632,16 @@ If the `result` parameter is a function and the timeout does not occur, the func
725
632
  Note: The rejection of the `operation` parameter is not handled by this function.
726
633
  You may want to handle it outside this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously."
727
634
 
728
- ###### Type parameters
635
+ ###### Type Parameters
729
636
 
730
- | Name |
731
- | :------ |
637
+ | Type Parameter |
638
+ | ------ |
732
639
  | `T` |
733
640
 
734
641
  ###### Parameters
735
642
 
736
- | Name | Type | Description |
737
- | :------ | :------ | :------ |
643
+ | Parameter | Type | Description |
644
+ | ------ | ------ | ------ |
738
645
  | `operation` | `Promise`\<`T`\> \| () => `Promise`\<`T`\> | The original Promise or a function that returns a Promise to which the timeout will be applied. |
739
646
  | `ms` | `number` | The number of milliseconds for the timeout. |
740
647
  | `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> | The result to resolve with if the timeout occurs, or a function that supplies the result. |
@@ -745,32 +652,34 @@ You may want to handle it outside this function to avoid warnings like "(node:43
745
652
 
746
653
  A new Promise that resolves to the specified result if the timeout occurs.
747
654
 
748
- ___
655
+ ***
749
656
 
750
- ##### withConcurrency
657
+ <a id="api-withconcurrency"></a>
751
658
 
752
- `Static` **withConcurrency**\<`Data`, `Result`\>(`concurrency`, `jobs`, `operation`): `Promise`\<`Result`[]\>
659
+ ##### withConcurrency()
660
+
661
+ > `static` **withConcurrency**\<`Data`, `Result`\>(`concurrency`, `jobs`, `operation`): `Promise`\<`Result`[]\>
753
662
 
754
663
  Executes multiple jobs/operations with a specified level of concurrency.
755
664
 
756
665
  Unlike `inParallel(...)`, this function may throw or reject an error when a job/operation fails.
757
666
  When an error is re-thrown, remaining operations will not be executed.
758
- If you want all the operations to always be executed, use [inParallel](#inparallel) instead.
667
+ If you want all the operations to always be executed, use [PromiseUtils.inParallel](#api-inparallel) instead.
759
668
 
760
- ###### Type parameters
669
+ ###### Type Parameters
761
670
 
762
- | Name | Description |
763
- | :------ | :------ |
671
+ | Type Parameter | Description |
672
+ | ------ | ------ |
764
673
  | `Data` | The type of the job data, typically an Array. |
765
674
  | `Result` | The type of the return value from the operation function. |
766
675
 
767
676
  ###### Parameters
768
677
 
769
- | Name | Type | Description |
770
- | :------ | :------ | :------ |
678
+ | Parameter | Type | Description |
679
+ | ------ | ------ | ------ |
771
680
  | `concurrency` | `number` | The number of jobs/operations to run concurrently. |
772
681
  | `jobs` | `Iterable`\<`Data`\> | The job data to be processed. This function can handle an infinite or unknown number of elements safely. |
773
- | `operation` | (`job`: `Data`, `index`: `number`) => `Promise`\<`Result`\> | The function that processes job data asynchronously. |
682
+ | `operation` | (`job`, `index`) => `Promise`\<`Result`\> | The function that processes job data asynchronously. |
774
683
 
775
684
  ###### Returns
776
685
 
@@ -779,7 +688,7 @@ If you want all the operations to always be executed, use [inParallel](#inparall
779
688
  A promise that resolves to an array containing the results from the operation function.
780
689
  The results in the returned array are in the same order as the corresponding elements in the jobs array.
781
690
 
782
- **`Example`**
691
+ ###### Example
783
692
 
784
693
  ```ts
785
694
  // At any time, there would be no more than 5 concurrency API calls. Error would be re-thrown immediately when it occurs.
@@ -789,28 +698,30 @@ const attributes = await PromiseUtils.withConcurrency(5, topicArns, async (topic
789
698
  });
790
699
  ```
791
700
 
792
- ___
701
+ ***
702
+
703
+ <a id="api-withretry"></a>
793
704
 
794
- ##### withRetry
705
+ ##### withRetry()
795
706
 
796
- `Static` **withRetry**\<`Result`, `TError`\>(`operation`, `backoff`, `shouldRetry?`): `Promise`\<`Result`\>
707
+ > `static` **withRetry**\<`Result`, `TError`\>(`operation`, `backoff`, `shouldRetry`): `Promise`\<`Result`\>
797
708
 
798
709
  Repeatedly performs an operation until a specified criteria is met.
799
710
 
800
- ###### Type parameters
711
+ ###### Type Parameters
801
712
 
802
- | Name | Type | Description |
803
- | :------ | :------ | :------ |
804
- | `Result` | `Result` | Type of the operation result. |
713
+ | Type Parameter | Default type | Description |
714
+ | ------ | ------ | ------ |
715
+ | `Result` | - | Type of the operation result. |
805
716
  | `TError` | `any` | Type of the possible error that could be generated by the operation. |
806
717
 
807
718
  ###### Parameters
808
719
 
809
- | Name | Type | Description |
810
- | :------ | :------ | :------ |
811
- | `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. |
812
- | `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. |
813
- | `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. |
720
+ | Parameter | Type | Description |
721
+ | ------ | ------ | ------ |
722
+ | `operation` | (`attempt`, `previousResult`, `previousError`) => `Promise`\<`Result`\> | A function that outputs a Promise result. Typically, the operation does not use its arguments. |
723
+ | `backoff` | `number`[] \| (`attempt`, `previousResult`, `previousError`) => `number` \| `undefined` | 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. |
724
+ | `shouldRetry` | (`previousError`, `previousResult`, `attempt`) => `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. |
814
725
 
815
726
  ###### Returns
816
727
 
@@ -818,7 +729,7 @@ Repeatedly performs an operation until a specified criteria is met.
818
729
 
819
730
  A promise of the operation result, potentially with retries applied.
820
731
 
821
- **`Example`**
732
+ ###### Example
822
733
 
823
734
  ```ts
824
735
  const result = await PromiseUtils.withRetry(() => doSomething(), [100, 200, 300, 500, 800, 1000]);
@@ -826,30 +737,970 @@ const result2 = await PromiseUtils.withRetry(() => doSomething(), Array.from({le
826
737
  const result3 = await PromiseUtils.withRetry(() => doSomething(), attempt => attempt <= 8 ? 1000 * Math.min(FIBONACCI_SEQUENCE[attempt - 1], 10) : undefined, err => err.statusCode === 429);
827
738
  ```
828
739
 
829
- ## Enums
740
+ ## Type Aliases
741
+
742
+
743
+ <a id="type-aliasespromisestatetypemd"></a>
744
+
745
+ ### Type Alias: PromiseStateType
746
+
747
+ > **PromiseStateType** = keyof *typeof* [`PromiseState`](#variablespromisestate-1md)
748
+
749
+ ## Variables
750
+
751
+
752
+ <a id="variablesexponential_sequencemd"></a>
753
+
754
+ ### Variable: EXPONENTIAL\_SEQUENCE
755
+
756
+ > `const` **EXPONENTIAL\_SEQUENCE**: `number`[]
757
+
758
+ Array of 25 exponential numbers starting from 1 up to 33554432.
759
+ It can be used to form your own backoff interval array.
760
+
761
+ #### Example
762
+
763
+ ```ts
764
+ // 1ms, 2ms, 4ms, 8ms, 16ms, 32ms
765
+ PromiseUtils.withRetry(() => doSomething(), EXPONENTIAL_SEQUENCE.slice(0, 5), err => err.statusCode === 429);
766
+ // 1s, 2s, 4s, 8s, 10s, 10s, 10s, 10s, 10s, 10s
767
+ PromiseUtils.withRetry(() => doSomething(), Array.from({length: 10}, (_v, i) => 1000 * Math.min(EXPONENTIAL_SEQUENCE[i], 10)), err => err.statusCode === 429);
768
+ // with +-10% randomness: 1s, 2s, 4s, 8s
769
+ PromiseUtils.withRetry(() => doSomething(), FIBONACCI_SEQUENCE.slice(0, 4).map(n => 1000 * n * (1 + (Math.random() - 0.5) / 5)), err => err.statusCode === 429);
770
+ ```
771
+
772
+
773
+ <a id="variablesfibonacci_sequencemd"></a>
774
+
775
+ ### Variable: FIBONACCI\_SEQUENCE
776
+
777
+ > `const` **FIBONACCI\_SEQUENCE**: `number`[]
778
+
779
+ Array of 25 Fibonacci numbers starting from 1 up to 317811.
780
+ It can be used to form your own backoff interval array.
781
+
782
+ #### Example
783
+
784
+ ```ts
785
+ // 1ms, 2ms, 3ms, 5ms, 8ms, 13ms
786
+ PromiseUtils.withRetry(() => doSomething(), FIBONACCI_SEQUENCE.slice(0, 5), err => err.statusCode === 429);
787
+ // 1s, 2s, 3s, 4s, 8s, 10s, 10s, 10s, 10s, 10s
788
+ PromiseUtils.withRetry(() => doSomething(), Array.from({length: 10}, (_v, i) => 1000 * Math.min(FIBONACCI_SEQUENCE[i], 10)), err => err.statusCode === 429);
789
+ // with +-10% randomness: 1s, 2s, 3s, 5s, 8s, 13s
790
+ PromiseUtils.withRetry(() => doSomething(), FIBONACCI_SEQUENCE.slice(0, 5).map(n => 1000 * n * (1 + (Math.random() - 0.5) / 5)), err => err.statusCode === 429);
791
+ ```
792
+
830
793
 
794
+ <a id="variablespromisestate-1md"></a>
831
795
 
832
- <a name="enumspromisestatemd"></a>
796
+ ### Variable: PromiseState
833
797
 
834
- ### Enumeration: PromiseState
798
+ > `const` **PromiseState**: `object`
835
799
 
836
800
  The state of a Promise can only be one of: Pending, Fulfilled, and Rejected.
837
801
 
838
- #### Enumeration Members
802
+ #### Type Declaration
803
+
804
+ | Name | Type | Default value |
805
+ | ------ | ------ | ------ |
806
+ | <a id="api-fulfilled"></a> `Fulfilled` | `"Fulfilled"` | `'Fulfilled'` |
807
+ | <a id="api-pending"></a> `Pending` | `"Pending"` | `'Pending'` |
808
+ | <a id="api-rejected"></a> `Rejected` | `"Rejected"` | `'Rejected'` |
809
+
810
+
811
+ <a id="variablescancellabledelayedrejectmd"></a>
812
+
813
+ ### Variable: cancellableDelayedReject()
814
+
815
+ > `const` **cancellableDelayedReject**: \<`T`, `R`\>(`ms`, `reason`) => `object` = `PromiseUtils.cancellableDelayedReject`
816
+
817
+ Creates a cancellable timer that will reject after a specified number of milliseconds.
839
818
 
840
- ##### Fulfilled
819
+ The returned object contains:
820
+ - stop() to cancel the scheduled rejection (if called before the timer fires). Calling
821
+ stop() prevents the promise from being settled by this timer.
822
+ - promise which will reject with the supplied reason (or the value returned by the
823
+ reason function) after ms milliseconds unless stop() is called first.
841
824
 
842
- **Fulfilled** = ``"Fulfilled"``
825
+ If the reason is a PromiseLike that rejects, its rejection value will be used as the rejection reason.
843
826
 
844
- ___
827
+ Creates a cancellable timer that will reject after a specified number of milliseconds.
845
828
 
846
- ##### Pending
829
+ The returned object contains:
830
+ - `stop()` to cancel the scheduled rejection (if called before the timer fires). Calling
831
+ `stop()` prevents the promise from being settled by this timer.
832
+ - `promise` which will reject with the supplied `reason` (or the value returned by the
833
+ `reason` function) after `ms` milliseconds unless `stop()` is called first.
847
834
 
848
- **Pending** = ``"Pending"``
835
+ If the `reason` is a PromiseLike that rejects, its rejection value will be used as the rejection reason.
849
836
 
850
- ___
837
+ #### Type Parameters
851
838
 
852
- ##### Rejected
839
+ | Type Parameter | Default type |
840
+ | ------ | ------ |
841
+ | `T` | `never` |
842
+ | `R` | `any` |
843
+
844
+ #### Parameters
845
+
846
+ | Parameter | Type | Description |
847
+ | ------ | ------ | ------ |
848
+ | `ms` | `number` | The number of milliseconds after which the scheduled rejection will occur. |
849
+ | `reason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> | The reason for the rejection, or a function that supplies the reason. |
853
850
 
854
- **Rejected** = ``"Rejected"``
851
+ #### Returns
852
+
853
+ `object`
854
+
855
+ An object with `stop()` and `promise`.
856
+
857
+ | Name | Type |
858
+ | ------ | ------ |
859
+ | `promise` | `Promise`\<`T`\> |
860
+ | `stop()` | () => `void` |
861
+
862
+ #### Param
863
+
864
+ The number of milliseconds after which the scheduled rejection will occur.
865
+
866
+ #### Param
867
+
868
+ The reason for the rejection, or a function that supplies the reason.
869
+
870
+ #### Returns
871
+
872
+ An object with stop() and promise.
873
+
874
+
875
+ <a id="variablescancellabledelayedresolvemd"></a>
876
+
877
+ ### Variable: cancellableDelayedResolve()
878
+
879
+ > `const` **cancellableDelayedResolve**: \<`T`\>(`ms`, `result?`) => `object` = `PromiseUtils.cancellableDelayedResolve`
880
+
881
+ Creates a cancellable timer that will resolve after a specified number of milliseconds.
882
+
883
+ The returned object contains:
884
+ - stop() to cancel the scheduled resolution (if called before the timer fires). Calling
885
+ stop() prevents the promise from being settled by this timer.
886
+ - promise which will resolve with the supplied result (or the value returned by the
887
+ result function) after ms milliseconds unless stop() is called first.
888
+
889
+ If the result is a PromiseLike, its resolution value will be used as the resolved value.
890
+
891
+ Creates a cancellable timer that will resolve after a specified number of milliseconds.
892
+
893
+ The returned object contains:
894
+ - `stop()` to cancel the scheduled resolution (if called before the timer fires). Calling
895
+ `stop()` prevents the promise from being settled by this timer.
896
+ - `promise` which will resolve with the supplied `result` (or the value returned by the
897
+ `result` function) after `ms` milliseconds unless `stop()` is called first.
898
+
899
+ Note: If the `result` is a function that returns a Promise, the returned `promise` will
900
+ resolve with that Promise's resolution (i.e. it behaves like resolving with a PromiseLike).
901
+
902
+ #### Type Parameters
903
+
904
+ | Type Parameter |
905
+ | ------ |
906
+ | `T` |
907
+
908
+ #### Parameters
909
+
910
+ | Parameter | Type | Description |
911
+ | ------ | ------ | ------ |
912
+ | `ms` | `number` | The number of milliseconds after which the scheduled resolution will occur. |
913
+ | `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> | The result to be resolved by the Promise, or a function that supplies the result. |
914
+
915
+ #### Returns
916
+
917
+ `object`
918
+
919
+ An object with `stop()` and `promise`.
920
+
921
+ | Name | Type |
922
+ | ------ | ------ |
923
+ | `promise` | `Promise`\<`T`\> |
924
+ | `stop()` | () => `void` |
925
+
926
+ #### Param
927
+
928
+ The number of milliseconds after which the scheduled resolution will occur.
929
+
930
+ #### Param
931
+
932
+ The result to be resolved by the Promise, or a function that supplies the result.
933
+
934
+ #### Returns
935
+
936
+ An object with stop() and promise.
937
+
938
+
939
+ <a id="variablesdelayedrejectmd"></a>
940
+
941
+ ### Variable: delayedReject()
942
+
943
+ > `const` **delayedReject**: \<`T`, `R`\>(`ms`, `reason`) => `Promise`\<`T`\> = `PromiseUtils.delayedReject`
944
+
945
+ Creates a Promise that rejects after a specified number of milliseconds.
946
+
947
+ The reason argument may be:
948
+ - a value to reject with,
949
+ - a PromiseLike whose rejection will be adopted by the returned Promise, or
950
+ - a function which is invoked when the timer fires and may return a value or a PromiseLike.
951
+
952
+ If reason is a function, it is called when the timer elapses; if it returns a Promise,
953
+ the returned Promise will reject with that Promise's rejection reason (or reject with the
954
+ returned value if it resolves).
955
+
956
+ Creates a Promise that rejects after a specified number of milliseconds.
957
+
958
+ The `reason` argument may be:
959
+ - a value to reject with,
960
+ - a PromiseLike whose rejection will be adopted by the returned Promise, or
961
+ - a function which is invoked when the timer fires and may return a value or a PromiseLike.
962
+
963
+ If `reason` is a function, it is called when the timer elapses; if it returns a Promise,
964
+ the returned Promise will reject with that Promise's rejection reason (or reject with the
965
+ returned value if it resolves).
966
+
967
+ #### Type Parameters
968
+
969
+ | Type Parameter | Default type |
970
+ | ------ | ------ |
971
+ | `T` | `never` |
972
+ | `R` | `any` |
973
+
974
+ #### Parameters
975
+
976
+ | Parameter | Type | Description |
977
+ | ------ | ------ | ------ |
978
+ | `ms` | `number` | The number of milliseconds after which the created Promise will reject. |
979
+ | `reason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> | The reason for the rejection, or a function that supplies the reason. |
980
+
981
+ #### Returns
982
+
983
+ `Promise`\<`T`\>
984
+
985
+ A Promise that rejects with the specified reason after the specified delay.
986
+
987
+ #### Param
988
+
989
+ The number of milliseconds after which the created Promise will reject.
990
+
991
+ #### Param
992
+
993
+ The reason for the rejection, or a function that supplies the reason.
994
+
995
+ #### Returns
996
+
997
+ A Promise that rejects with the specified reason after the specified delay.
998
+
999
+
1000
+ <a id="variablesdelayedresolvemd"></a>
1001
+
1002
+ ### Variable: delayedResolve()
1003
+
1004
+ > `const` **delayedResolve**: \<`T`\>(`ms`, `result?`) => `Promise`\<`T`\> = `PromiseUtils.delayedResolve`
1005
+
1006
+ Creates a Promise that resolves after a specified number of milliseconds.
1007
+
1008
+ The result argument may be:
1009
+ - a value to resolve with,
1010
+ - a PromiseLike whose resolution will be adopted by the returned Promise, or
1011
+ - a function which is invoked when the timer fires and may return a value or a PromiseLike.
1012
+
1013
+ If result is a function, it is called when the timer elapses; if it returns a Promise,
1014
+ the returned Promise will adopt that Promise's outcome.
1015
+
1016
+ Creates a Promise that resolves after a specified number of milliseconds.
1017
+
1018
+ The `result` argument may be:
1019
+ - a value to resolve with,
1020
+ - a PromiseLike whose resolution will be adopted by the returned Promise, or
1021
+ - a function which is invoked when the timer fires and may return a value or a PromiseLike.
1022
+
1023
+ If `result` is a function, it is called when the timer elapses; if it returns a Promise,
1024
+ the returned Promise will adopt that Promise's outcome.
1025
+
1026
+ #### Type Parameters
1027
+
1028
+ | Type Parameter |
1029
+ | ------ |
1030
+ | `T` |
1031
+
1032
+ #### Parameters
1033
+
1034
+ | Parameter | Type | Description |
1035
+ | ------ | ------ | ------ |
1036
+ | `ms` | `number` | The number of milliseconds after which the created Promise will resolve. |
1037
+ | `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> | The result to be resolved by the Promise, or a function that supplies the result. |
1038
+
1039
+ #### Returns
1040
+
1041
+ `Promise`\<`T`\>
1042
+
1043
+ A Promise that resolves with the specified result after the specified delay.
1044
+
1045
+ #### Param
1046
+
1047
+ The number of milliseconds after which the created Promise will resolve.
1048
+
1049
+ #### Param
1050
+
1051
+ The result to be resolved by the Promise, or a function that supplies the result.
1052
+
1053
+ #### Returns
1054
+
1055
+ A Promise that resolves with the specified result after the specified delay.
1056
+
1057
+
1058
+ <a id="variablesinparallelmd"></a>
1059
+
1060
+ ### Variable: inParallel()
1061
+
1062
+ > `const` **inParallel**: \<`Data`, `Result`, `TError`\>(`parallelism`, `jobs`, `operation`, `options?`) => `Promise`\<(`Result` \| `TError`)[]\> = `PromiseUtils.inParallel`
1063
+
1064
+ Executes multiple jobs/operations in parallel. By default, all operations are executed regardless of any failures.
1065
+ In most cases, using withConcurrency might be more convenient.
1066
+
1067
+ By default, this function does not throw or reject an error when any job/operation fails.
1068
+ Errors from operations are returned alongside results in the returned array.
1069
+ This function only resolves when all jobs/operations are settled (either resolved or rejected).
1070
+
1071
+ If options.abortOnError is set to true, this function throws (or rejects with) an error immediately when any job/operation fails.
1072
+ In this mode, some jobs/operations may not be executed if one fails.
1073
+
1074
+ Executes multiple jobs/operations in parallel. By default, all operations are executed regardless of any failures.
1075
+ In most cases, using [PromiseUtils.withConcurrency](#withconcurrency) might be more convenient.
1076
+
1077
+ By default, this function does not throw or reject an error when any job/operation fails.
1078
+ Errors from operations are returned alongside results in the returned array.
1079
+ This function only resolves when all jobs/operations are settled (either resolved or rejected).
1080
+
1081
+ If `options.abortOnError` is set to true, this function throws (or rejects with) an error immediately when any job/operation fails.
1082
+ In this mode, some jobs/operations may not be executed if one fails.
1083
+
1084
+ #### Type Parameters
1085
+
1086
+ | Type Parameter | Default type | Description |
1087
+ | ------ | ------ | ------ |
1088
+ | `Data` | - | The type of the job data, typically an Array. |
1089
+ | `Result` | - | The type of the return value from the operation function. |
1090
+ | `TError` | `Result` | The type for the error that could be thrown from the operation function, defaults to `Result`. |
1091
+
1092
+ #### Parameters
1093
+
1094
+ | Parameter | Type | Description |
1095
+ | ------ | ------ | ------ |
1096
+ | `parallelism` | `number` | The number of jobs/operations to run concurrently. |
1097
+ | `jobs` | `Iterable`\<`Data`\> | The job data to be processed. This function can safely handle an infinite or unknown number of elements. |
1098
+ | `operation` | (`job`, `index`) => `Promise`\<`Result`\> | The function that processes job data asynchronously. |
1099
+ | `options?` | \{ `abortOnError`: `boolean`; \} | Options to control the function's behavior. |
1100
+ | `options.abortOnError?` | `boolean` | If true, the function aborts and throws an error on the first failed operation. |
1101
+
1102
+ #### Returns
1103
+
1104
+ `Promise`\<(`Result` \| `TError`)[]\>
1105
+
1106
+ A promise that resolves to an array containing the results of the operations.
1107
+ Each element is either a fulfilled result or a rejected error/reason.
1108
+ The results or errors in the returned array are in the same order as the corresponding elements in the jobs array.
1109
+
1110
+ #### Example
1111
+
1112
+ ```ts
1113
+ // Capture errors in the returned array
1114
+ const attributesAndPossibleErrors: Array<JobResult|JobError> = await PromiseUtils.inParallel(5, topicArns, async (topicArn) => {
1115
+ const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;
1116
+ return topicAttributes;
1117
+ });
1118
+
1119
+ // Abort on the first error
1120
+ let results: Array<JobResult>;
1121
+ try {
1122
+ results = await PromiseUtils.inParallel(100, jobs, async (job) => processor.process(job), { abortOnError: true });
1123
+ } catch (error) {
1124
+ // handle the error
1125
+ }
1126
+ ```
1127
+
1128
+ #### Param
1129
+
1130
+ The number of jobs/operations to run concurrently.
1131
+
1132
+ #### Param
1133
+
1134
+ The job data to be processed. This function can safely handle an infinite or unknown number of elements.
1135
+
1136
+ #### Param
1137
+
1138
+ The function that processes job data asynchronously.
1139
+
1140
+ #### Param
1141
+
1142
+ Options to control the function's behavior.
1143
+
1144
+ #### Param
1145
+
1146
+ If true, the function aborts and throws an error on the first failed operation.
1147
+
1148
+ #### Returns
1149
+
1150
+ A promise that resolves to an array containing the results of the operations.
1151
+ Each element is either a fulfilled result or a rejected error/reason.
1152
+ The results or errors in the returned array are in the same order as the corresponding elements in the jobs array.
1153
+
1154
+
1155
+ <a id="variablespromisestatemd"></a>
1156
+
1157
+ ### Variable: promiseState()
1158
+
1159
+ > `const` **promiseState**: (`p`) => `Promise`\<`"Pending"` \| `"Fulfilled"` \| `"Rejected"`\> = `PromiseUtils.promiseState`
1160
+
1161
+ Retrieves the state of the specified Promise.
1162
+ Note: The returned value is a Promise that resolves immediately.
1163
+
1164
+ Retrieves the state of the specified Promise.
1165
+ Note: The returned value is a Promise that resolves immediately.
1166
+
1167
+ #### Parameters
1168
+
1169
+ | Parameter | Type | Description |
1170
+ | ------ | ------ | ------ |
1171
+ | `p` | `Promise`\<`any`\> | The Promise whose state is to be determined. |
1172
+
1173
+ #### Returns
1174
+
1175
+ `Promise`\<`"Pending"` \| `"Fulfilled"` \| `"Rejected"`\>
1176
+
1177
+ A Promise that resolves immediately with the state of the input Promise.
1178
+
1179
+ #### Param
1180
+
1181
+ The Promise whose state is to be determined.
1182
+
1183
+ #### Returns
1184
+
1185
+ A Promise that resolves immediately with the state of the input Promise.
1186
+
1187
+
1188
+ <a id="variablesrepeatmd"></a>
1189
+
1190
+ ### Variable: repeat()
1191
+
1192
+ > `const` **repeat**: \<`Result`, `Param`, `Collection`\>(`operation`, `nextParameter`, `collect`, `initialCollection`, `initialParameter`) => `Promise`\<`Collection`\> = `PromiseUtils.repeat`
1193
+
1194
+ Executes an operation repeatedly and collects all the results.
1195
+ This function is very useful for many scenarios, such like client-side pagination.
1196
+
1197
+ Executes an operation repeatedly and collects all the results.
1198
+ This function is very useful for many scenarios, such like client-side pagination.
1199
+
1200
+ #### Type Parameters
1201
+
1202
+ | Type Parameter | Description |
1203
+ | ------ | ------ |
1204
+ | `Result` | The type of the operation result. |
1205
+ | `Param` | The type of the input to the operation, typically a paging parameter. |
1206
+ | `Collection` | The type of the collection returned by this function. |
1207
+
1208
+ #### Parameters
1209
+
1210
+ | Parameter | Type | Description |
1211
+ | ------ | ------ | ------ |
1212
+ | `operation` | (`parameter`) => `Promise`\<`Result`\> | A function that takes a parameter as input and returns a result. Typically, the parameter has optional fields to control paging. |
1213
+ | `nextParameter` | (`response`) => `Partial`\<`Param`\> \| `Promise`\<`Partial`\<`Param`\>\> \| `null` | 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. |
1214
+ | `collect` | (`collection`, `result`) => `Collection` | A function for merging the operation result into the collection. |
1215
+ | `initialCollection` | `Collection` | The initial collection, which will be the first argument passed to the first invocation of the collect function. |
1216
+ | `initialParameter` | `Partial`\<`Param`\> | The parameter for the first operation. |
1217
+
1218
+ #### Returns
1219
+
1220
+ `Promise`\<`Collection`\>
1221
+
1222
+ A promise that resolves to a collection of all the results returned by the operation function.
1223
+
1224
+ #### Example
1225
+
1226
+ ```ts
1227
+ const domainNameObjects = await PromiseUtils.repeat(
1228
+ pagingParam => apig.getDomainNames({limit: 500, ...pagingParam}).promise(),
1229
+ response => response.position? {position: response.position} : null,
1230
+ (collection, response) => collection.concat(response.items!),
1231
+ [] as APIGateway.DomainName[],
1232
+ );
1233
+ ```
1234
+
1235
+ #### Param
1236
+
1237
+ A function that takes a parameter as input and returns a result. Typically, the parameter has optional fields to control paging.
1238
+
1239
+ #### Param
1240
+
1241
+ 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.
1242
+
1243
+ #### Param
1244
+
1245
+ A function for merging the operation result into the collection.
1246
+
1247
+ #### Param
1248
+
1249
+ The initial collection, which will be the first argument passed to the first invocation of the collect function.
1250
+
1251
+ #### Param
1252
+
1253
+ The parameter for the first operation.
1254
+
1255
+ #### Returns
1256
+
1257
+ A promise that resolves to a collection of all the results returned by the operation function.
1258
+
1259
+
1260
+ <a id="variablesrunperiodicallymd"></a>
1261
+
1262
+ ### Variable: runPeriodically()
1263
+
1264
+ > `const` **runPeriodically**: \<`T`\>(`operation`, `interval`, `options?`) => `object` = `PromiseUtils.runPeriodically`
1265
+
1266
+ Runs an operation periodically with configurable intervals and stopping conditions.
1267
+
1268
+ - `interval` may be a single number (ms), an array of numbers, or a function
1269
+ that receives the iteration number (starting at 1) and returns the next
1270
+ interval in milliseconds or `undefined` to stop.
1271
+ - If the interval array runs out of elements or the function returns `undefined`
1272
+ (or a negative value), no further invocations will be scheduled.
1273
+
1274
+ Options:
1275
+ - `maxExecutions` stop after N runs (inclusive).
1276
+ - `maxDurationMs` stop after elapsed ms since the first scheduled start.
1277
+ - `schedule` controls how the interval is measured:
1278
+ - `'delayAfterEnd'`: wait the interval after the previous operation completes
1279
+ before scheduling the next one (equivalent to a fixed delay between ends).
1280
+ - `'delayBetweenStarts'`: keep start times on a regular schedule (interval measured
1281
+ between the starts of successive operations).
1282
+ The default schedule is `'delayBetweenStarts'`.
1283
+
1284
+ Returns an object with `stop()` to cancel further executions and `done` which
1285
+ resolves when the periodic runner stops. If the provided `operation` throws or
1286
+ rejects, the `done` promise will reject with that error so callers can handle it.
1287
+
1288
+ Note: The first invocation of `operation` is scheduled after the first interval
1289
+ elapses (i.e. this function does NOT call `operation` immediately). If you need
1290
+ an immediate run, invoke `operation(1)` yourself before calling `runPeriodically`.
1291
+
1292
+ Runs an operation periodically with configurable intervals and stopping conditions.
1293
+
1294
+ - `interval` may be a single number (ms), an array of numbers, or a function
1295
+ that receives the iteration number (starting at 1) and returns the next
1296
+ interval in milliseconds or `undefined` to stop.
1297
+ - If the interval array runs out of elements or the function returns `undefined`
1298
+ (or a negative value), no further invocations will be scheduled.
1299
+
1300
+ Options:
1301
+ - `maxExecutions` stop after N runs (inclusive).
1302
+ - `maxDurationMs` stop after elapsed ms since the first scheduled start.
1303
+ - `schedule` controls how the interval is measured:
1304
+ - `'delayAfterEnd'`: wait the interval after the previous operation completes
1305
+ before scheduling the next one (equivalent to a fixed delay between ends).
1306
+ - `'delayBetweenStarts'`: keep start times on a regular schedule (interval measured
1307
+ between the starts of successive operations).
1308
+ The default schedule is `'delayBetweenStarts'`.
1309
+
1310
+ Returns an object with `stop()` to cancel further executions and `done` which
1311
+ resolves when the periodic runner stops. If the provided `operation` throws or
1312
+ rejects, the `done` promise will reject with that error so callers can handle it.
1313
+
1314
+ Note: The first invocation of `operation` is scheduled after the first interval
1315
+ elapses (i.e. this function does NOT call `operation` immediately). If you need
1316
+ an immediate run, invoke `operation(1)` yourself before calling `runPeriodically`.
1317
+
1318
+ #### Type Parameters
1319
+
1320
+ | Type Parameter | Description |
1321
+ | ------ | ------ |
1322
+ | `T` | The operation return type (ignored by the runner; used for typing). |
1323
+
1324
+ #### Parameters
1325
+
1326
+ | Parameter | Type | Description |
1327
+ | ------ | ------ | ------ |
1328
+ | `operation` | (`iteration`) => `T` \| `Promise`\<`T`\> | Function to run each iteration. Receives the iteration index (1-based). |
1329
+ | `interval` | `number` \| `number`[] \| (`iteration`) => `number` \| `undefined` | Number | number[] | ((iteration: number) => number|undefined) defining waits. |
1330
+ | `options?` | \{ `maxDurationMs?`: `number`; `maxExecutions?`: `number`; `schedule?`: `"delayAfterEnd"` \| `"delayBetweenStarts"`; \} | Optional configuration. |
1331
+ | `options.maxDurationMs?` | `number` | Stop after N milliseconds. |
1332
+ | `options.maxExecutions?` | `number` | Stop after N executions. |
1333
+ | `options.schedule?` | `"delayAfterEnd"` \| `"delayBetweenStarts"` | How to measure intervals: `'delayAfterEnd'` or `'delayBetweenStarts'`. |
1334
+
1335
+ #### Returns
1336
+
1337
+ `object`
1338
+
1339
+ An object containing `stop()` to cancel further executions and `done` Promise
1340
+ which resolves when the periodic runner stops (or rejects if the operation errors).
1341
+
1342
+ | Name | Type |
1343
+ | ------ | ------ |
1344
+ | `done` | `Promise`\<`void`\> |
1345
+ | `stop()` | () => `void` |
1346
+
1347
+ #### Template
1348
+
1349
+ The operation return type (ignored by the runner; used for typing).
1350
+
1351
+ #### Param
1352
+
1353
+ Function to run each iteration. Receives the iteration index (1-based).
1354
+
1355
+ #### Param
1356
+
1357
+ Number | number[] | ((iteration: number) => number|undefined) defining waits.
1358
+
1359
+ #### Param
1360
+
1361
+ Optional configuration.
1362
+
1363
+ #### Param
1364
+
1365
+ Stop after N executions.
1366
+
1367
+ #### Param
1368
+
1369
+ Stop after N milliseconds.
1370
+
1371
+ #### Param
1372
+
1373
+ How to measure intervals: `'delayAfterEnd'` or `'delayBetweenStarts'`.
1374
+
1375
+ #### Returns
1376
+
1377
+ An object containing `stop()` to cancel further executions and `done` Promise
1378
+ which resolves when the periodic runner stops (or rejects if the operation errors).
1379
+
1380
+
1381
+ <a id="variablessynchronisedmd"></a>
1382
+
1383
+ ### Variable: synchronised()
1384
+
1385
+ > `const` **synchronised**: \<`T`\>(`lock`, `operation`) => `Promise`\<`T`\> = `PromiseUtils.synchronised`
1386
+
1387
+ This is just another spelling of synchronized.
1388
+
1389
+ This is just another spelling of [PromiseUtils.synchronized](#synchronized).
1390
+
1391
+ #### Type Parameters
1392
+
1393
+ | Type Parameter |
1394
+ | ------ |
1395
+ | `T` |
1396
+
1397
+ #### Parameters
1398
+
1399
+ | Parameter | Type | Description |
1400
+ | ------ | ------ | ------ |
1401
+ | `lock` | `any` | The object (such as a string, a number, or `this` in a class) used to identify the lock. |
1402
+ | `operation` | (`previousState`, `previousSettledState`, `previousResult`) => `Promise`\<`T`\> | The function that performs the computation and returns a Promise. |
1403
+
1404
+ #### Returns
1405
+
1406
+ `Promise`\<`T`\>
1407
+
1408
+ The result of the operation function.
1409
+
1410
+ #### Param
1411
+
1412
+ The object (such as a string, a number, or this in a class) used to identify the lock.
1413
+
1414
+ #### Param
1415
+
1416
+ The function that performs the computation and returns a Promise.
1417
+
1418
+ #### Returns
1419
+
1420
+ The result of the operation function.
1421
+
1422
+
1423
+ <a id="variablessynchronizedmd"></a>
1424
+
1425
+ ### Variable: synchronized()
1426
+
1427
+ > `const` **synchronized**: \<`T`\>(`lock`, `operation`) => `Promise`\<`T`\> = `PromiseUtils.synchronized`
1428
+
1429
+ Provides mutual exclusion similar to synchronized in Java.
1430
+ Ensures no concurrent execution of any operation function associated with the same lock.
1431
+ The operation function has access to the state (when synchronized is called),
1432
+ settledState (when the operation function is called),
1433
+ and result (either the fulfilled result or the rejected reason) of the previous operation.
1434
+ If there is no previous invocation, state, settledState, and result will all be undefined.
1435
+
1436
+ Provides mutual exclusion similar to `synchronized` in Java.
1437
+ Ensures no concurrent execution of any operation function associated with the same lock.
1438
+ The operation function has access to the state (when `synchronized` is called),
1439
+ settledState (when the operation function is called),
1440
+ and result (either the fulfilled result or the rejected reason) of the previous operation.
1441
+ If there is no previous invocation, state, settledState, and result will all be undefined.
1442
+
1443
+ #### Type Parameters
1444
+
1445
+ | Type Parameter |
1446
+ | ------ |
1447
+ | `T` |
1448
+
1449
+ #### Parameters
1450
+
1451
+ | Parameter | Type | Description |
1452
+ | ------ | ------ | ------ |
1453
+ | `lock` | `any` | The object (such as a string, a number, or `this` in a class) used to identify the lock. |
1454
+ | `operation` | (`previousState`, `previousSettledState`, `previousResult`) => `Promise`\<`T`\> | The function that performs the computation and returns a Promise. |
1455
+
1456
+ #### Returns
1457
+
1458
+ `Promise`\<`T`\>
1459
+
1460
+ The result of the operation function.
1461
+
1462
+ #### Param
1463
+
1464
+ The object (such as a string, a number, or this in a class) used to identify the lock.
1465
+
1466
+ #### Param
1467
+
1468
+ The function that performs the computation and returns a Promise.
1469
+
1470
+ #### Returns
1471
+
1472
+ The result of the operation function.
1473
+
1474
+
1475
+ <a id="variablestimeoutrejectmd"></a>
1476
+
1477
+ ### Variable: timeoutReject()
1478
+
1479
+ > `const` **timeoutReject**: \<`T`, `R`\>(`operation`, `ms`, `rejectReason`) => `Promise`\<`T`\> = `PromiseUtils.timeoutReject`
1480
+
1481
+ Applies a timeout to a Promise or a function that returns a Promise.
1482
+ If the timeout occurs, the returned Promise rejects with the specified reason.
1483
+ If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
1484
+ If the rejectReason parameter is a function and the timeout does not occur, the function will not be called.
1485
+ 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."
1486
+
1487
+ Applies a timeout to a Promise or a function that returns a Promise.
1488
+ If the timeout occurs, the returned Promise rejects with the specified reason.
1489
+ If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
1490
+ If the `rejectReason` parameter is a function and the timeout does not occur, the function will not be called.
1491
+ 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."
1492
+
1493
+ #### Type Parameters
1494
+
1495
+ | Type Parameter | Default type |
1496
+ | ------ | ------ |
1497
+ | `T` | `never` |
1498
+ | `R` | `any` |
1499
+
1500
+ #### Parameters
1501
+
1502
+ | Parameter | Type | Description |
1503
+ | ------ | ------ | ------ |
1504
+ | `operation` | `Promise`\<`T`\> \| () => `Promise`\<`T`\> | The original Promise or a function that returns a Promise to which the timeout will be applied. |
1505
+ | `ms` | `number` | The number of milliseconds for the timeout. |
1506
+ | `rejectReason` | `R` \| `PromiseLike`\<`R`\> \| () => `R` \| `PromiseLike`\<`R`\> | The reason to reject with if the timeout occurs, or a function that supplies the reason. |
1507
+
1508
+ #### Returns
1509
+
1510
+ `Promise`\<`T`\>
1511
+
1512
+ A new Promise that rejects with the specified reason if the timeout occurs.
1513
+
1514
+ #### Param
1515
+
1516
+ The original Promise or a function that returns a Promise to which the timeout will be applied.
1517
+
1518
+ #### Param
1519
+
1520
+ The number of milliseconds for the timeout.
1521
+
1522
+ #### Param
1523
+
1524
+ The reason to reject with if the timeout occurs, or a function that supplies the reason.
1525
+
1526
+ #### Returns
1527
+
1528
+ A new Promise that rejects with the specified reason if the timeout occurs.
1529
+
1530
+
1531
+ <a id="variablestimeoutresolvemd"></a>
1532
+
1533
+ ### Variable: timeoutResolve()
1534
+
1535
+ > `const` **timeoutResolve**: \<`T`\>(`operation`, `ms`, `result?`) => `Promise`\<`T`\> = `PromiseUtils.timeoutResolve`
1536
+
1537
+ Applies a timeout to a Promise or a function that returns a Promise.
1538
+ If the timeout occurs, the returned Promise resolves to the specified result.
1539
+ If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
1540
+ If the result parameter is a function and the timeout does not occur, the function will not be called.
1541
+ Note: The rejection of the operation parameter is not handled by this function.
1542
+ You may want to handle it outside this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously."
1543
+
1544
+ Applies a timeout to a Promise or a function that returns a Promise.
1545
+ If the timeout occurs, the returned Promise resolves to the specified result.
1546
+ If the timeout does not occur, the returned Promise resolves or rejects based on the outcome of the original Promise.
1547
+ If the `result` parameter is a function and the timeout does not occur, the function will not be called.
1548
+ Note: The rejection of the `operation` parameter is not handled by this function.
1549
+ You may want to handle it outside this function to avoid warnings like "(node:4330) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously."
1550
+
1551
+ #### Type Parameters
1552
+
1553
+ | Type Parameter |
1554
+ | ------ |
1555
+ | `T` |
1556
+
1557
+ #### Parameters
1558
+
1559
+ | Parameter | Type | Description |
1560
+ | ------ | ------ | ------ |
1561
+ | `operation` | `Promise`\<`T`\> \| () => `Promise`\<`T`\> | The original Promise or a function that returns a Promise to which the timeout will be applied. |
1562
+ | `ms` | `number` | The number of milliseconds for the timeout. |
1563
+ | `result?` | `T` \| `PromiseLike`\<`T`\> \| () => `T` \| `PromiseLike`\<`T`\> | The result to resolve with if the timeout occurs, or a function that supplies the result. |
1564
+
1565
+ #### Returns
1566
+
1567
+ `Promise`\<`T`\>
1568
+
1569
+ A new Promise that resolves to the specified result if the timeout occurs.
1570
+
1571
+ #### Param
1572
+
1573
+ The original Promise or a function that returns a Promise to which the timeout will be applied.
1574
+
1575
+ #### Param
1576
+
1577
+ The number of milliseconds for the timeout.
1578
+
1579
+ #### Param
1580
+
1581
+ The result to resolve with if the timeout occurs, or a function that supplies the result.
1582
+
1583
+ #### Returns
1584
+
1585
+ A new Promise that resolves to the specified result if the timeout occurs.
1586
+
1587
+
1588
+ <a id="variableswithconcurrencymd"></a>
1589
+
1590
+ ### Variable: withConcurrency()
1591
+
1592
+ > `const` **withConcurrency**: \<`Data`, `Result`\>(`concurrency`, `jobs`, `operation`) => `Promise`\<`Result`[]\> = `PromiseUtils.withConcurrency`
1593
+
1594
+ Executes multiple jobs/operations with a specified level of concurrency.
1595
+
1596
+ Executes multiple jobs/operations with a specified level of concurrency.
1597
+
1598
+ Unlike `inParallel(...)`, this function may throw or reject an error when a job/operation fails.
1599
+ When an error is re-thrown, remaining operations will not be executed.
1600
+ If you want all the operations to always be executed, use [PromiseUtils.inParallel](#inparallel) instead.
1601
+
1602
+ #### Type Parameters
1603
+
1604
+ | Type Parameter | Description |
1605
+ | ------ | ------ |
1606
+ | `Data` | The type of the job data, typically an Array. |
1607
+ | `Result` | The type of the return value from the operation function. |
1608
+
1609
+ #### Parameters
1610
+
1611
+ | Parameter | Type | Description |
1612
+ | ------ | ------ | ------ |
1613
+ | `concurrency` | `number` | The number of jobs/operations to run concurrently. |
1614
+ | `jobs` | `Iterable`\<`Data`\> | The job data to be processed. This function can handle an infinite or unknown number of elements safely. |
1615
+ | `operation` | (`job`, `index`) => `Promise`\<`Result`\> | The function that processes job data asynchronously. |
1616
+
1617
+ #### Returns
1618
+
1619
+ `Promise`\<`Result`[]\>
1620
+
1621
+ A promise that resolves to an array containing the results from the operation function.
1622
+ The results in the returned array are in the same order as the corresponding elements in the jobs array.
1623
+
1624
+ #### Example
1625
+
1626
+ ```ts
1627
+ // At any time, there would be no more than 5 concurrency API calls. Error would be re-thrown immediately when it occurs.
1628
+ const attributes = await PromiseUtils.withConcurrency(5, topicArns, async (topicArn) => {
1629
+ const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;
1630
+ return topicAttributes;
1631
+ });
1632
+ ```
1633
+
1634
+ #### Param
1635
+
1636
+ The number of jobs/operations to run concurrently.
1637
+
1638
+ #### Param
1639
+
1640
+ The job data to be processed. This function can handle an infinite or unknown number of elements safely.
1641
+
1642
+ #### Param
1643
+
1644
+ The function that processes job data asynchronously.
1645
+
1646
+ #### Returns
1647
+
1648
+ A promise that resolves to an array containing the results from the operation function.
1649
+ The results in the returned array are in the same order as the corresponding elements in the jobs array.
1650
+
1651
+
1652
+ <a id="variableswithretrymd"></a>
1653
+
1654
+ ### Variable: withRetry()
1655
+
1656
+ > `const` **withRetry**: \<`Result`, `TError`\>(`operation`, `backoff`, `shouldRetry`) => `Promise`\<`Result`\> = `PromiseUtils.withRetry`
1657
+
1658
+ Repeatedly performs an operation until a specified criteria is met.
1659
+
1660
+ Repeatedly performs an operation until a specified criteria is met.
1661
+
1662
+ #### Type Parameters
1663
+
1664
+ | Type Parameter | Default type | Description |
1665
+ | ------ | ------ | ------ |
1666
+ | `Result` | - | Type of the operation result. |
1667
+ | `TError` | `any` | Type of the possible error that could be generated by the operation. |
1668
+
1669
+ #### Parameters
1670
+
1671
+ | Parameter | Type | Description |
1672
+ | ------ | ------ | ------ |
1673
+ | `operation` | (`attempt`, `previousResult`, `previousError`) => `Promise`\<`Result`\> | A function that outputs a Promise result. Typically, the operation does not use its arguments. |
1674
+ | `backoff` | `number`[] \| (`attempt`, `previousResult`, `previousError`) => `number` \| `undefined` | 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. |
1675
+ | `shouldRetry` | (`previousError`, `previousResult`, `attempt`) => `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. |
1676
+
1677
+ #### Returns
1678
+
1679
+ `Promise`\<`Result`\>
1680
+
1681
+ A promise of the operation result, potentially with retries applied.
1682
+
1683
+ #### Example
1684
+
1685
+ ```ts
1686
+ const result = await PromiseUtils.withRetry(() => doSomething(), [100, 200, 300, 500, 800, 1000]);
1687
+ const result2 = await PromiseUtils.withRetry(() => doSomething(), Array.from({length: 10}, (_v, i) => 1000 * Math.min(FIBONACCI_SEQUENCE[i], 10), err => err.statusCode === 429);
1688
+ const result3 = await PromiseUtils.withRetry(() => doSomething(), attempt => attempt <= 8 ? 1000 * Math.min(FIBONACCI_SEQUENCE[attempt - 1], 10) : undefined, err => err.statusCode === 429);
1689
+ ```
1690
+
1691
+ #### Param
1692
+
1693
+ A function that outputs a Promise result. Typically, the operation does not use its arguments.
1694
+
1695
+ #### Param
1696
+
1697
+ An array of retry backoff periods (in milliseconds) or a function for calculating them.
1698
+
1699
+ #### Param
1700
+
1701
+ A predicate function for deciding whether another call to the operation should occur.
1702
+
1703
+ #### Returns
1704
+
1705
+ A promise of the operation result, potentially with retries applied.
855
1706
  <!-- API end -->