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 1 commit
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
Next Next commit
Mention AbortSignal
fregante authored Dec 30, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit 326f6a8dc5367da71b138efd4b539157a1ee06f5
28 changes: 28 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -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
@@ -156,3 +159,28 @@ 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 conveniently be 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))
```