Skip to content

Commit 870db0f

Browse files
committed
Support options object in pLimit()
Fixes #89
1 parent 1fb1407 commit 870db0f

4 files changed

Lines changed: 41 additions & 3 deletions

File tree

index.d.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,10 @@ export type LimitFunction = {
5151
/**
5252
Run multiple promise-returning & async functions with limited concurrency.
5353
54-
@param concurrency - Concurrency limit. Minimum: `1`.
54+
@param concurrency - Concurrency limit. Minimum: `1`. Can also be an options object.
5555
@returns A `limit` function.
5656
*/
57-
export default function pLimit(concurrency: number): LimitFunction;
57+
export default function pLimit(concurrency: number | Options): LimitFunction;
5858

5959
export type Options = {
6060
/**

index.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import Queue from 'yocto-queue';
22

33
export default function pLimit(concurrency) {
4+
if (typeof concurrency === 'object') {
5+
concurrency = concurrency.concurrency;
6+
}
7+
48
validateConcurrency(concurrency);
59

610
const queue = new Queue();

readme.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,19 @@ Returns a `limit` function.
3636

3737
#### concurrency
3838

39-
Type: `number`\
39+
Type: `number | object`\
4040
Minimum: `1`
4141

4242
Concurrency limit.
4343

44+
You can pass a number or an options object with a `concurrency` property:
45+
46+
```js
47+
import pLimit from 'p-limit';
48+
49+
const limit = pLimit({concurrency: 1});
50+
```
51+
4452
### limit(fn, ...args)
4553

4654
Returns the promise returned by calling `fn(...args)`.

test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,24 @@ test('map accepts an iterable (array iterator)', async t => {
208208
t.deepEqual(results, [2, 4, 6, 8]);
209209
});
210210

211+
test('accepts options object', async t => {
212+
const limit = pLimit({concurrency: 1});
213+
214+
const input = [
215+
limit(async () => {
216+
await delay(50);
217+
return 1;
218+
}),
219+
limit(async () => {
220+
await delay(50);
221+
return 2;
222+
}),
223+
];
224+
225+
t.deepEqual(await Promise.all(input), [1, 2]);
226+
t.is(limit.concurrency, 1);
227+
});
228+
211229
test('throws on invalid concurrency argument', t => {
212230
t.throws(() => {
213231
pLimit(0);
@@ -228,6 +246,14 @@ test('throws on invalid concurrency argument', t => {
228246
t.throws(() => {
229247
pLimit(true);
230248
});
249+
250+
t.throws(() => {
251+
pLimit({});
252+
});
253+
254+
t.throws(() => {
255+
pLimit({concurrency: 0});
256+
});
231257
});
232258

233259
test('change concurrency to smaller value', async t => {

0 commit comments

Comments
 (0)