feat(async/delay): add persistent option (#2527)

This commit is contained in:
Asher Gomez 2022-08-22 23:09:53 +10:00 committed by GitHub
parent ca1f90b154
commit d7cd0080b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 1 deletions

View File

@ -195,3 +195,13 @@ export function ListenerUnref(
throw new TypeError("Requires --unstable"); throw new TypeError("Requires --unstable");
} }
} }
export function unrefTimer(
...args: Parameters<typeof Deno.unrefTimer>
): ReturnType<typeof Deno.unrefTimer> {
if (typeof Deno.unrefTimer == "function") {
return Deno.unrefTimer(...args);
} else {
throw new TypeError("Requires --unstable");
}
}

View File

@ -135,6 +135,17 @@ const result = await delayedPromise;
// ... // ...
``` ```
To allow the process to continue to run as long as the timer exists. Requires
`--unstable` flag.
```typescript
import { delay } from "https://deno.land/std@$STD_VERSION/async/mod.ts";
// ...
await delay(100, { persistent: false });
// ...
```
## MuxAsyncIterator ## MuxAsyncIterator
The MuxAsyncIterator class multiplexes multiple async iterators into a single The MuxAsyncIterator class multiplexes multiple async iterators into a single

View File

@ -1,13 +1,16 @@
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible. // This module is browser compatible.
import { unrefTimer } from "../_deno_unstable.ts";
export interface DelayOptions { export interface DelayOptions {
signal?: AbortSignal; signal?: AbortSignal;
/** Indicates whether the process should continue to run as long as the timer exists. This is `true` by default. */
persistent?: boolean;
} }
/* Resolves after the given number of milliseconds. */ /* Resolves after the given number of milliseconds. */
export function delay(ms: number, options: DelayOptions = {}): Promise<void> { export function delay(ms: number, options: DelayOptions = {}): Promise<void> {
const { signal } = options; const { signal, persistent } = options;
if (signal?.aborted) { if (signal?.aborted) {
return Promise.reject(new DOMException("Delay was aborted.", "AbortError")); return Promise.reject(new DOMException("Delay was aborted.", "AbortError"));
} }
@ -22,5 +25,8 @@ export function delay(ms: number, options: DelayOptions = {}): Promise<void> {
}; };
const i = setTimeout(done, ms); const i = setTimeout(done, ms);
signal?.addEventListener("abort", abort, { once: true }); signal?.addEventListener("abort", abort, { once: true });
if (persistent === false) {
unrefTimer(i);
}
}); });
} }