Skip to content

Commit

Permalink
Merge 0d5fac9 into 618303b
Browse files Browse the repository at this point in the history
  • Loading branch information
zzdjk6 committed Mar 22, 2020
2 parents 618303b + 0d5fac9 commit 00edcda
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
36 changes: 35 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ There are 2 ways to create an `AbortablePromise`:
#### Constructor

```typescript
const abortablePromise = new AbortablePromise<T>((resolve, resolve, abortSignal) => {
const abortablePromise = new AbortablePromise<T>((resolve, reject, abortSignal) => {
// ...
});
```
Expand All @@ -45,3 +45,37 @@ abortablePromise.abort();
// Abort with custom reason
abortablePromise.abort('I abort it');
```

## Receipes

### Use with fetch

```typescript
const loadData = (id: number) => {
retrun new AbortablePromise<Data>((resolve, reject, abortSignal) => {
fetch(url, { signal: abortSignal })
.then(response => response.json())
.then(parseJsonToData)
.then(resolve)
.catch(reject);
});
}

const abortablePromise = loadData(id);
abortablePromise.abort();
```

### Do something more when abort

```typescript
const abortablePromise = new AbortablePromise<Data>((resolve, reject, abortSignal) => {
abortSignal.addEventListener('abort', () => {
// Do something
});
// ...
});
```

## More

More background explain is available on my [blog](https://medium.com/@zzdjk6/a-simple-implementation-of-abortable-promise-using-abortcontroller-with-typescript-2c163ee050e8).
28 changes: 28 additions & 0 deletions src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,34 @@ describe('AbortablePromise', () => {
}
});

it('can do something more when abort', async () => {
expect.assertions(3);

const mockFn1 = jest.fn();
const mockFn2 = jest.fn();

const abortablePromise = new AbortablePromise<number>((resolve, _, abortSignal) => {
setTimeout(() => resolve(500), 500);
abortSignal.onabort = () => {
mockFn1();
};
abortSignal.addEventListener('abort', () => {
mockFn2();
});
});

setTimeout(() => abortablePromise.abort(), 200);

try {
await abortablePromise;
} catch (e) {
expect(e).toBeInstanceOf(AbortError);
}

expect(mockFn1).toBeCalledTimes(1);
expect(mockFn2).toBeCalledTimes(1);
});

it('can be created from existing promise', async () => {
expect.assertions(4);
const promise = new Promise<number>(resolve => {
Expand Down

0 comments on commit 00edcda

Please sign in to comment.