Skip to content
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): add deadline to async module #1022

Merged
merged 1 commit into from
Jul 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions async/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,16 @@ const [branch1, branch2] = tee(gen());
}
})();
```

## deadline

Create a promise which will be rejected with `DeadlineError` when a given delay
is exceeded.

```typescript
import { deadline } from "https://deno.land/std/async/mod.ts";

const delayedPromise = delay(1000);
// Below throws `DeadlineError` after 10 ms
const result = await deadline(delayedPromise, 10);
```
18 changes: 18 additions & 0 deletions async/deadline.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { deferred } from "./deferred.ts";

export class DeadlineError extends Error {
wperron marked this conversation as resolved.
Show resolved Hide resolved
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]);
}
20 changes: 20 additions & 0 deletions async/deadline_test.ts
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);
});
1 change: 1 addition & 0 deletions async/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from "./delay.ts";
export * from "./mux_async_iterator.ts";
export * from "./pool.ts";
export * from "./tee.ts";
export * from "./deadline.ts";