-
Notifications
You must be signed in to change notification settings - Fork 633
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
feat(async/unstable): add waitFor
function to wait for condition to be true (#6213)
#6230
Open
acrodrig
wants to merge
4
commits into
denoland:main
Choose a base branch
from
acrodrig:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
3b02a17
Adding waitFor function to async module (plus one typo fix)
acrodrig 0645adb
Fixing clearing of timeout leak
acrodrig 66cf455
Ignoring the leak in the docs example (as it add no knowledge value a…
acrodrig 32764c1
Update async/unstable_wait_for.ts
kt3k File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. | ||
// This module is browser compatible. | ||
|
||
import { deadline } from "./deadline.ts"; | ||
|
||
/** Options for {@linkcode waitFor}. */ | ||
export interface WaitForOptions { | ||
/** Signal used to abort the waitFor. */ | ||
signal?: AbortSignal; | ||
/** Indicates the step jump in time to wait for the predicate to be true. | ||
* | ||
* @default {100} | ||
*/ | ||
step?: number; | ||
} | ||
|
||
/** | ||
* Resolve a {@linkcode Promise} after a given predicate becomes true or the | ||
* timeout amount of milliseconds has been reached. | ||
* | ||
* @throws {DOMException} If signal is aborted before either the waitFor | ||
* predicate is true or the timeout duration was reached, and `signal.reason` | ||
* is undefined. | ||
* @param predicate a Nullary (no arguments) function returning a boolean | ||
* @param ms Duration in milliseconds for how long the waitFor should last. | ||
* @param options Additional options. | ||
* | ||
* @example Basic usage | ||
* ```ts ignore | ||
* import { waitFor } from "@std/async/unstable-wait-for"; | ||
* | ||
* // Deno server to acknowledge reception of request/webhook | ||
* let requestReceived = false; | ||
* Deno.serve((_req) => { | ||
* requestReceived = true; | ||
* return new Response("Hello, world"); | ||
* }); | ||
* | ||
* // ... | ||
* waitFor(() => requestReceived, 10000); | ||
* // If less than 10 seconds pass, the requestReceived flag will be true | ||
* // assert(requestReceived); | ||
* // ... | ||
* ``` | ||
*/ | ||
export function waitFor( | ||
predicate: () => boolean | Promise<boolean>, | ||
ms: number, | ||
options: WaitForOptions = {}, | ||
): Promise<void> { | ||
const { step = 100 } = options; | ||
|
||
// Create a new promise that resolves when the predicate is true | ||
let interval: number; | ||
const p: Promise<void> = new Promise(function (resolve) { | ||
interval = setInterval(() => { | ||
if (predicate()) resolve(); | ||
}, step); | ||
}); | ||
|
||
// Return a deadline promise | ||
return deadline(p, ms, options).finally(() => clearInterval(interval)); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. | ||
import { assertAlmostEquals, assertEquals, assertRejects } from "@std/assert"; | ||
import { waitFor } from "./unstable_wait_for.ts"; | ||
|
||
// NOT detecting leaks means that the internal interval was correctly cleared | ||
|
||
Deno.test("waitFor() returns fulfilled promise", async () => { | ||
let flag = false; | ||
setTimeout(() => flag = true, 100); | ||
const start = Date.now(); | ||
await waitFor(() => flag === true, 1000); | ||
// Expects the promise to be resolved after 100ms | ||
assertAlmostEquals(Date.now() - start, 100, 10); | ||
}); | ||
|
||
Deno.test("waitFor() throws DOMException on timeout", async () => { | ||
let flag = false; | ||
const id = setTimeout(() => flag = true, 1000); | ||
const start = Date.now(); | ||
const error = await assertRejects( | ||
() => waitFor(() => flag === true, 100), | ||
DOMException, | ||
"Signal timed out.", | ||
); | ||
assertAlmostEquals(Date.now() - start, 100, 10); | ||
assertEquals(error.name, "TimeoutError"); | ||
clearTimeout(id); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍