- From: Benjamin Gruenbaum <notifications@github.com>
- Date: Thu, 04 Feb 2021 11:21:24 -0800
- To: whatwg/dom <dom@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <whatwg/dom/issues/946/773546318@github.com>
@jakearchibald sure, that's a good question/point.
Here are two quick examples:
----
With timers (since they're the simplest API):
```js
// before
async function setTimeout(ms, { signal } = {}) {
return await new Promise((resolve) => {
const timer = setTimeout(() => {
signal?.removeEventListener("abort", listener);
resolve();
}, ms);
const listener = () => clearTimeout(timer); // maybe reject too
if (signal?.aborted) {
listener();
} else {
signal?.addEventListener("abort", listener);
}
});
}
```
After:
```js
// after
async function setTimeout(ms, { signal } = {}) {
return await new Promise((resolve) => {
const timer = setTimeout(() => {
resolve();
}, ms);
// works in Node.js since timers are objects
aborted(signal, timer).then(() => clearTimeout(timer)); // maybe reject too
});
}
```
-----
With a database layer:
```js
class DB {
// wraps a database with AbortSignal API support
async query(string, { signal } = {}) {
await this.open();
const query = this.createQuery(string);
if (signal?.aborted) {
query.cancel(new AbortError());
} else {
signal?.addEventListener('abort', () => {
query.cancel(new AbortError());
});
}
return await query.promise();
}
// rest of the implementation
}
```
After:
```js
class DB {
// wraps a database with AbortSignal API support
async query(string, { signal } = {}) {
await this.open();
const query = this.createQuery(string);
aborted(signal, query).then(() => query.cancel(new AbortError()))
return await query.promise();
}
// rest of the implementation
}
```
Let me know if the examples are what you had in mind or you had something else in mind :]
--
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/946#issuecomment-773546318
Received on Thursday, 4 February 2021 19:21:36 UTC