Skip to content

Commit

Permalink
feat(async): add status to deferred promises (#1047)
Browse files Browse the repository at this point in the history
  • Loading branch information
lowlighter authored Jul 22, 2021
1 parent 0722cd0 commit 3ea4939
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
16 changes: 14 additions & 2 deletions async/deferred.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// See https://github.com/Microsoft/TypeScript/issues/15202
// At the time of writing, the github issue is closed but the problem remains.
export interface Deferred<T> extends Promise<T> {
status: "pending" | "fulfilled" | "rejected";
resolve(value?: T | PromiseLike<T>): void;
// deno-lint-ignore no-explicit-any
reject(reason?: any): void;
Expand All @@ -20,7 +21,18 @@ export interface Deferred<T> extends Promise<T> {
export function deferred<T>(): Deferred<T> {
let methods;
const promise = new Promise<T>((resolve, reject): void => {
methods = { resolve, reject };
methods = {
async resolve(value: T | PromiseLike<T>) {
await value;
Object.assign(promise, { status: "fulfilled" });
resolve(value);
},
// deno-lint-ignore no-explicit-any
reject(reason?: any) {
Object.assign(promise, { status: "rejected" });
reject(reason);
},
};
});
return Object.assign(promise, methods) as Deferred<T>;
return Object.assign(promise, methods, { status: "pending" }) as Deferred<T>;
}
15 changes: 15 additions & 0 deletions async/deferred_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,29 @@ import { deferred } from "./deferred.ts";

Deno.test("[async] deferred: resolve", async function () {
const d = deferred<string>();
assertEquals(d.status, "pending");
d.resolve("🦕");
assertEquals(await d, "🦕");
assertEquals(d.status, "fulfilled");
});

Deno.test("[async] deferred: reject", async function () {
const d = deferred<number>();
assertEquals(d.status, "pending");
d.reject(new Error("A deno error 🦕"));
await assertThrowsAsync(async () => {
await d;
});
assertEquals(d.status, "rejected");
});

Deno.test("[async] deferred: status with promised value", async function () {
const d = deferred<string>();
const e = deferred<string>();
assertEquals(d.status, "pending");
d.resolve(e);
assertEquals(d.status, "pending");
e.resolve("🦕");
assertEquals(await d, "🦕");
assertEquals(d.status, "fulfilled");
});

0 comments on commit 3ea4939

Please sign in to comment.