Skip to content

Commit

Permalink
Added tests
Browse files Browse the repository at this point in the history
  • Loading branch information
smikhalevski committed Mar 11, 2024
1 parent 18d156c commit 27a309e
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ Provide a custom abort reason:
promise.abort(new Error('Operation aborted'));
```

Abort promise if an external signal is aborted:

```ts
promise.withSignal(signal);
```

# `Deferred`

The promise that can be resolved externally.
Expand Down
8 changes: 6 additions & 2 deletions src/main/AbortablePromise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,13 @@ export class AbortablePromise<T> extends Promise<T> {
* @returns This promise.
*/
withSignal(signal: AbortSignal): this {
signal.addEventListener('abort', () => {
if (signal.aborted) {
this.abort(signal.reason);
});
} else {
signal.addEventListener('abort', () => {
this.abort(signal.reason);
});
}
return this;
}
}
44 changes: 44 additions & 0 deletions src/test/AbortablePromise.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,48 @@ describe('AbortablePromise', () => {
await expect(promise).resolves.toBe(111);
expect(promise['_abortController'].signal.aborted).toBe(true);
});

test('aborts if signal is aborted asynchronously', async () => {
const promise = new AbortablePromise(() => {});
const abortController = new AbortController();

promise.withSignal(abortController.signal);

abortController.abort(111);

await expect(promise).rejects.toBe(abortController.signal.reason);
});

test('does not abort if an external signal is not aborted', async () => {
const promise = new AbortablePromise(resolve => {
resolve(111);
});
const abortController = new AbortController();

promise.withSignal(abortController.signal);

await expect(promise).resolves.toBe(111);
});

test('aborts if an external signal is aborted asynchronously', async () => {
const promise = new AbortablePromise(() => {});
const abortController = new AbortController();

promise.withSignal(abortController.signal);

abortController.abort(111);

await expect(promise).rejects.toBe(abortController.signal.reason);
});

test('aborts if an external signal is aborted before subscription', async () => {
const promise = new AbortablePromise(() => {});
const abortController = new AbortController();

abortController.abort(111);

promise.withSignal(abortController.signal);

await expect(promise).rejects.toBe(abortController.signal.reason);
});
});

0 comments on commit 27a309e

Please sign in to comment.