Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,12 @@ export class Sema {
}

release(token?: any): void {
if (this.waiting.length === 0 && this.free.length >= this.nrTokens) {
throw new Error(
'Sema#release() was called more times than Sema#acquire()'
);
}

this.releaseEmitter.emit('release', this.noTokens ? '1' : token);
}

Expand Down
18 changes: 18 additions & 0 deletions test/sema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,24 @@ test('tryAcquire returns undefined', async () => {
expect(s.tryAcquire()).toBeUndefined();
});

test('release throws when called without an acquired token', () => {
const s = new Sema(1);

expect(() => s.release()).toThrow(
'Sema#release() was called more times than Sema#acquire()'
);
});

test('release does not increase available tokens beyond the limit', async () => {
const s = new Sema(1);

await s.acquire();
s.release();

expect(s.tryAcquire()).toBeDefined();
expect(s.tryAcquire()).toBeUndefined();
});

test('Pausing works', () => {
const pauseFn = jest.fn();
const resumeFn = jest.fn();
Expand Down