|
| 1 | +// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. |
| 2 | +// This module is browser compatible. |
| 3 | + |
| 4 | +import { deadline } from "./deadline.ts"; |
| 5 | + |
| 6 | +/** Options for {@linkcode waitFor}. */ |
| 7 | +export interface WaitForOptions { |
| 8 | + /** Signal used to abort the waitFor. */ |
| 9 | + signal?: AbortSignal; |
| 10 | + /** Indicates the step jump in time to wait for the predicate to be true. |
| 11 | + * |
| 12 | + * @default {100} |
| 13 | + */ |
| 14 | + step?: number; |
| 15 | +} |
| 16 | + |
| 17 | +/** |
| 18 | + * Resolve a {@linkcode Promise} after a given predicate becomes true or the |
| 19 | + * timeout amount of milliseconds has been reached. |
| 20 | + * |
| 21 | + * @throws {DOMException} If signal is aborted before either the waitFor |
| 22 | + * predicate is true or the timeout duration was reached, and `signal.reason` |
| 23 | + * is undefined. |
| 24 | + * @param predicate a Nullary (no arguments) function returning a boolean |
| 25 | + * @param ms Duration in milliseconds for how long the waitFor should last. |
| 26 | + * @param options Additional options. |
| 27 | + * |
| 28 | + * @example Basic usage |
| 29 | + * ```ts ignore |
| 30 | + * import { waitFor } from "@std/async/unstable-wait-for"; |
| 31 | + * |
| 32 | + * // Deno server to acknowledge reception of request/webhook |
| 33 | + * let requestReceived = false; |
| 34 | + * Deno.serve((_req) => { |
| 35 | + * requestReceived = true; |
| 36 | + * return new Response("Hello, world"); |
| 37 | + * }); |
| 38 | + * |
| 39 | + * // ... |
| 40 | + * waitFor(() => requestReceived, 10000); |
| 41 | + * // If less than 10 seconds pass, the requestReceived flag will be true |
| 42 | + * // assert(requestReceived); |
| 43 | + * // ... |
| 44 | + * ``` |
| 45 | + */ |
| 46 | +export function waitFor( |
| 47 | + predicate: () => boolean | Promise<boolean>, |
| 48 | + ms: number, |
| 49 | + options: WaitForOptions = {}, |
| 50 | +): Promise<void> { |
| 51 | + const { step = 100 } = options; |
| 52 | + |
| 53 | + // Create a new promise that resolves when the predicate is true |
| 54 | + let interval: number; |
| 55 | + const p: Promise<void> = new Promise(function (resolve) { |
| 56 | + interval = setInterval(() => { |
| 57 | + if (predicate()) resolve(); |
| 58 | + }, step); |
| 59 | + }); |
| 60 | + |
| 61 | + // Return a deadline promise |
| 62 | + return deadline(p, ms, options).finally(() => clearInterval(interval)); |
| 63 | +} |
0 commit comments