-
Notifications
You must be signed in to change notification settings - Fork 624
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(async): add
deadline
to async module
- Loading branch information
1 parent
09ce13c
commit 63a4edf
Showing
4 changed files
with
52 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { deferred } from "./deferred.ts"; | ||
|
||
export class DeadlineError extends Error { | ||
constructor() { | ||
super("Deadline"); | ||
this.name = "DeadlineError"; | ||
} | ||
} | ||
|
||
/** | ||
* Create a promise which will be rejected with DeadlineError when a given delay is exceeded. | ||
*/ | ||
export function deadline<T>(p: Promise<T>, delay: number): Promise<T> { | ||
const d = deferred<never>(); | ||
const t = setTimeout(() => d.reject(new DeadlineError()), delay); | ||
p.finally(() => clearTimeout(t)); | ||
return Promise.race([p, d]); | ||
} |
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,20 @@ | ||
import { assertEquals, assertThrowsAsync } from "../testing/asserts.ts"; | ||
import { deferred } from "./deferred.ts"; | ||
import { deadline, DeadlineError } from "./deadline.ts"; | ||
|
||
Deno.test("[async] deadline: return fulfilled promise", async () => { | ||
const p = deferred(); | ||
const t = setTimeout(() => p.resolve("Hello"), 100); | ||
const result = await deadline(p, 1000); | ||
assertEquals(result, "Hello"); | ||
clearTimeout(t); | ||
}); | ||
|
||
Deno.test("[async] deadline: throws DeadlineError", async () => { | ||
const p = deferred(); | ||
const t = setTimeout(() => p.resolve("Hello"), 1000); | ||
await assertThrowsAsync(async () => { | ||
await deadline(p, 100); | ||
}, DeadlineError); | ||
clearTimeout(t); | ||
}); |
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