Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/zzdjk6/simple-abortable-promise
A Simple Implementation of Abortable Promise
https://github.com/zzdjk6/simple-abortable-promise
Last synced: 2 months ago
JSON representation
A Simple Implementation of Abortable Promise
- Host: GitHub
- URL: https://github.com/zzdjk6/simple-abortable-promise
- Owner: zzdjk6
- License: mit
- Created: 2020-03-17T08:50:03.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-05T16:29:12.000Z (about 2 years ago)
- Last Synced: 2024-10-31T10:04:32.781Z (3 months ago)
- Language: TypeScript
- Size: 982 KB
- Stars: 6
- Watchers: 3
- Forks: 2
- Open Issues: 12
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# simple-abortable-promise [![Build Status](https://travis-ci.com/zzdjk6/simple-abortable-promise.svg?branch=master)](https://travis-ci.com/zzdjk6/simple-abortable-promise) [![Coverage Status](https://coveralls.io/repos/github/zzdjk6/simple-abortable-promise/badge.svg)](https://coveralls.io/github/zzdjk6/simple-abortable-promise)
A Simple Implementation of Abortable Promise
## Overview
This library provides a deadly simple implementation of making `Promise` abortable.
That is, an `AbortablePromise` is a `Promise` with the abitlity to be aborted.
When an `AbortablePromise` is aborted, it will reject with an `AbortError`.
## How to install?
```bash
npm install simple-abortable-promise
```## How to use?
### Creating
There are 2 ways to create an `AbortablePromise`:
#### Constructor
```typescript
const abortablePromise = new AbortablePromise((resolve, reject, abortSignal) => {
// ...
});
```#### Create from an existing Promise
```typescript
const abortablePromise = AbortablePromise.from(promise);
```### Abort
```typescript
// Abort with default reason - Aborted
abortablePromise.abort();// Abort with custom reason
abortablePromise.abort('I abort it');
```## Receipes
### Use with fetch
```typescript
const loadData = (id: number) => {
retrun new AbortablePromise((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((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).