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

Mention AbortSignal in readme #40

Merged
merged 6 commits into from
Jan 8, 2024
Merged
Changes from 2 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
32 changes: 32 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

> Timeout a promise after a specified amount of time

> [!NOTE]
> You might want to use `AbortSignal.timeout()` instead. [More info below](#abortsignal)

## Install

```sh
Expand Down Expand Up @@ -156,3 +159,32 @@ Exposed for instance checking and sub-classing.
- [p-min-delay](https://github.com/sindresorhus/p-min-delay) - Delay a promise a minimum amount of time
- [p-retry](https://github.com/sindresorhus/p-retry) - Retry a promise-returning function
- [More…](https://github.com/sindresorhus/promise-fun)

## AbortSignal

> Modern alternative to `p-timeout`

Asynchronous functions like `fetch` can accept an [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal), which can be conveniently created with [AbortSignal.timeout()](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static).

The advantage over `p-timeout` is that the promise-generating function (like `fetch`) is actually notified that the user is no longer expecting an answer, so it can interrupt its work and free resources.

```js
// Call API, timeout after 5 seconds
const response = await fetch('./my-api', {signal: AbortSignal.timeout(5000)});
```

```js
async function buildWall(signal) {
for (const brick of bricks) {
signal.throwIfAborted();
// Or: if (signal.aborted) return;

await layBrick();
}
}

// Stop long work after 60 seconds
await buildWall(AbortSignal.timeout(60_000))
```

You can also [combine multiple signals](https://github.com/fregante/abort-utils/blob/main/source/merge-signals.md), like when you have a timeout _and_ an `AbortController` triggered with a Cancel button click.