Skip to content

Commit

Permalink
Add activeCount and pendingCount properties to the limited functi…
Browse files Browse the repository at this point in the history
…on (#9)
  • Loading branch information
Oren Zomer authored and sindresorhus committed Dec 25, 2018
1 parent 56fcb83 commit 2a5d6db
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
12 changes: 11 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,15 @@ module.exports = concurrency => {
}
};

return (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
Object.defineProperties(generator, {
activeCount: {
get: () => activeCount
},
pendingCount: {
get: () => queue.length
}
});

return generator;
};
7 changes: 7 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ Any arguments to pass through to `fn`.

Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions.

### limit.activeCount

The number of promises that are currently running.

### limit.pendingCount

The number of promises that are waiting to run (i.e. their internal `fn` was not called yet).

## FAQ

Expand Down
29 changes: 29 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,32 @@ test('does not ignore errors', async t => {

await t.throwsAsync(Promise.all(promises), {is: error});
});

test('activeCount and pendingCount properties', async t => {
const limit = m(5);
t.is(limit.activeCount, 0);
t.is(limit.pendingCount, 0);

const runningPromise1 = limit(() => delay(1000));
t.is(limit.activeCount, 1);
t.is(limit.pendingCount, 0);

await runningPromise1;
t.is(limit.activeCount, 0);
t.is(limit.pendingCount, 0);

const immediatePromises = Array.from({length: 5}, () => limit(() => delay(1000)));
const delayedPromises = Array.from({length: 3}, () => limit(() => delay(1000)));

t.is(limit.activeCount, 5);
t.is(limit.pendingCount, 3);

await Promise.all(immediatePromises);
t.is(limit.activeCount, 3);
t.is(limit.pendingCount, 0);

await Promise.all(delayedPromises);

t.is(limit.activeCount, 0);
t.is(limit.pendingCount, 0);
});

0 comments on commit 2a5d6db

Please sign in to comment.