Skip to content

Commit

Permalink
Support AbortController (#161)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
Richienb and sindresorhus committed Feb 1, 2022
1 parent 35e2d38 commit 394153f
Show file tree
Hide file tree
Showing 6 changed files with 250 additions and 139 deletions.
5 changes: 2 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ jobs:
fail-fast: false
matrix:
node-version:
- 14
- 12
- 16
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- run: npm install
Expand Down
41 changes: 40 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ Note: If your items can potentially throw an exception, you must handle those er

Type: `Function`

Promise-returning/async function.
Promise-returning/async function. When executed, it will receive `{signal}` as the first argument.

#### options

Expand All @@ -131,6 +131,41 @@ Default: `0`

Priority of operation. Operations with greater priority will be scheduled first.

##### signal

[`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) for cancellation of the operation. When aborted, it will be removed from the queue and the `queue.add()` call will reject with an `AbortError`. If the operation is already running, the signal will need to be handled by the operation itself.

```js
import PQueue, {AbortError} from 'p-queue';
import got, {CancelError} from 'got';

const queue = new PQueue();

const controller = new AbortController();

try {
await queue.add(({signal}) => {
const request = got('https://sindresorhus.com');

signal.addEventListener('abort', () => {
request.cancel();
});

try {
return await request;
} catch (error) {
if (!(error instanceof CancelError)) {
throw error;
}
}
}, {signal: controller.signal});
} catch (error) {
if (!(error instanceof AbortError)) {
throw error;
}
}
```

#### .addAll(fns, options?)

Same as `.add()`, but accepts an array of sync or async functions and returns a promise that resolves when all functions are resolved.
Expand Down Expand Up @@ -327,6 +362,10 @@ await queue.add(() => delay(600));
//=> 'Task is completed. Size: 0 Pending: 0'
```

### AbortError

The error thrown by `queue.add()` when a job is aborted before it is run. See [`signal`](#signal).

## Advanced example

A more advanced example to help you understand the flow.
Expand Down
Loading

0 comments on commit 394153f

Please sign in to comment.