Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always run limited functions asynchronously #28

Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,13 @@ const pLimit = concurrency => {
};

const enqueue = (fn, resolve, ...args) => {
if (activeCount < concurrency) {
run(fn, resolve, ...args);
} else {
queue.push(run.bind(null, fn, resolve, ...args));
}
queue.push(run.bind(null, fn, resolve, ...args));
(async () => {
await Promise.resolve();
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved
if (activeCount < concurrency && queue.length > 0) {
queue.shift()();
}
})();
};

const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
Expand Down
8 changes: 7 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ test('activeCount and pendingCount properties', async t => {
t.is(limit.pendingCount, 0);

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

await Promise.resolve();
t.is(limit.activeCount, 1);
t.is(limit.pendingCount, 0);

Expand All @@ -108,6 +112,7 @@ test('activeCount and pendingCount properties', async t => {
const immediatePromises = Array.from({length: 5}, () => limit(() => delay(1000)));
const delayedPromises = Array.from({length: 3}, () => limit(() => delay(1000)));

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

Expand All @@ -121,12 +126,13 @@ test('activeCount and pendingCount properties', async t => {
t.is(limit.pendingCount, 0);
});

test('clearQueue', t => {
test('clearQueue', async t => {
const limit = pLimit(1);

Array.from({length: 1}, () => limit(() => delay(1000)));
Array.from({length: 3}, () => limit(() => delay(1000)));

await Promise.resolve();
t.is(limit.pendingCount, 3);
limit.clearQueue();
t.is(limit.pendingCount, 0);
Expand Down