Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support AbortController #161

Merged
merged 5 commits into from
Feb 1, 2022
Merged
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
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