Skip to content

Commit

Permalink
feat(async): add deadline to async module
Browse files Browse the repository at this point in the history
  • Loading branch information
lambdalisue committed Jul 12, 2021
1 parent 09ce13c commit 63a4edf
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 0 deletions.
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 {
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";

0 comments on commit 63a4edf

Please sign in to comment.