Skip to content

Commit

Permalink
fix(clearQueue): reject pending promises
Browse files Browse the repository at this point in the history
BREAKING CHANGE: when clearQueue() is called, promises for queued function calls will be rejected.

fix sindresorhus#25
  • Loading branch information
jedwards1211 committed Apr 21, 2020
1 parent a11f02b commit 4835cd9
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
11 changes: 7 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const pLimit = concurrency => {
activeCount--;

if (queue.length > 0) {
queue.shift()();
queue.shift().run();
}
};

Expand All @@ -27,15 +27,17 @@ const pLimit = concurrency => {
result.then(next, next);
};

const enqueue = (fn, resolve, ...args) => {
const enqueue = (fn, resolve, reject, ...args) => {
if (activeCount < concurrency) {
run(fn, resolve, ...args);
} else {
queue.push(run.bind(null, fn, resolve, ...args));
queue.push({run: run.bind(null, fn, resolve, ...args), reject});
}
};

const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
const generator = (fn, ...args) => new Promise(
(resolve, reject) => enqueue(fn, resolve, reject, ...args)
);
Object.defineProperties(generator, {
activeCount: {
get: () => activeCount
Expand All @@ -45,6 +47,7 @@ const pLimit = concurrency => {
},
clearQueue: {
value: () => {
queue.forEach(({reject}) => reject(new Error('queue cleared before function was invoked')));
queue.length = 0;
}
}
Expand Down
4 changes: 3 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,9 @@ test('clearQueue', t => {
const limit = pLimit(1);

Array.from({length: 1}, () => limit(() => delay(1000)));
Array.from({length: 3}, () => limit(() => delay(1000)));
Array.from({length: 3}, () => limit(() => delay(1000)).catch(
error => t.is(error.message, 'queue cleared before function was invoked')
));

t.is(limit.pendingCount, 3);
limit.clearQueue();
Expand Down

0 comments on commit 4835cd9

Please sign in to comment.