feat(async): expose asyncPromise and asyncAsyncIterable (#2034)

This commit is contained in:
Yoshiya Hinosawa 2022-03-17 14:09:32 +09:00 committed by GitHub
parent dbccc64488
commit a158cbbde4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 5 deletions

View File

@ -47,6 +47,50 @@ for await (const item of abortable(p(), c.signal)) {
}
```
## abortablePromise
`abortablePromise` takes the promise and `AbortSignal` and returns the
cancelable version of the promise.
```typescript
import { abortablePromise } from "https://deno.land/std@$STD_VERSION/async/mod.ts";
const request = fetch("https://example.com");
const c = new AbortController();
setTimeout(() => c.abort(), 100);
const p = abortablePromise(request, c.signal);
// The below throws if the request didn't resolve in 100ms
await p;
```
## abortableAsyncIterable
`abortableAsyncIterable` takes the async iterable and `AbortSignal` and returns
the cancelable version of the async iterable.
```typescript
import { abortableAsyncIterable } from "https://deno.land/std@$STD_VERSION/async/mod.ts";
import { delay } from "https://deno.land/std@$STD_VERSION/async/mod.ts";
const p = async function* () {
yield "Hello";
await delay(1000);
yield "World";
};
const c = new AbortController();
setTimeout(() => c.abort(), 100);
// Below throws `DOMException` after 100 ms
// and items become `["Hello"]`
const items: string[] = [];
for await (const item of abortableAsyncIterable(p(), c.signal)) {
items.push(item);
}
```
## debounce
Debounces a given function by a given time.

View File

@ -1,9 +1,7 @@
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
import { deferred } from "./deferred.ts";
/**
* Make Promise or AsyncIterable abortable with a given signal.
*/
/** Make Promise or AsyncIterable abortable with the given signal. */
export function abortable<T>(p: Promise<T>, signal: AbortSignal): Promise<T>;
export function abortable<T>(
p: AsyncIterable<T>,
@ -20,7 +18,11 @@ export function abortable<T>(
}
}
function abortablePromise<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
/** Make Promise abortable with the given signal. */
export function abortablePromise<T>(
p: Promise<T>,
signal: AbortSignal,
): Promise<T> {
if (signal.aborted) {
return Promise.reject(createAbortError(signal.reason));
}
@ -35,7 +37,8 @@ function abortablePromise<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
]);
}
async function* abortableAsyncIterable<T>(
/** Make AsyncIterable abortable with the given signal. */
export async function* abortableAsyncIterable<T>(
p: AsyncIterable<T>,
signal: AbortSignal,
): AsyncGenerator<T> {