From 3ea49398a295909690723dc105384be2688282e2 Mon Sep 17 00:00:00 2001 From: Simon Lecoq <22963968+lowlighter@users.noreply.github.com> Date: Thu, 22 Jul 2021 10:28:27 +0200 Subject: [PATCH] feat(async): add status to deferred promises (#1047) --- async/deferred.ts | 16 ++++++++++++++-- async/deferred_test.ts | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/async/deferred.ts b/async/deferred.ts index 9455d68aab1f..c3bfad28f681 100644 --- a/async/deferred.ts +++ b/async/deferred.ts @@ -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 extends Promise { + status: "pending" | "fulfilled" | "rejected"; resolve(value?: T | PromiseLike): void; // deno-lint-ignore no-explicit-any reject(reason?: any): void; @@ -20,7 +21,18 @@ export interface Deferred extends Promise { export function deferred(): Deferred { let methods; const promise = new Promise((resolve, reject): void => { - methods = { resolve, reject }; + methods = { + async resolve(value: T | PromiseLike) { + 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; + return Object.assign(promise, methods, { status: "pending" }) as Deferred; } diff --git a/async/deferred_test.ts b/async/deferred_test.ts index b2481723624c..80a51e90e5bf 100644 --- a/async/deferred_test.ts +++ b/async/deferred_test.ts @@ -4,14 +4,29 @@ import { deferred } from "./deferred.ts"; Deno.test("[async] deferred: resolve", async function () { const d = deferred(); + assertEquals(d.status, "pending"); d.resolve("🦕"); assertEquals(await d, "🦕"); + assertEquals(d.status, "fulfilled"); }); Deno.test("[async] deferred: reject", async function () { const d = deferred(); + 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(); + const e = deferred(); + assertEquals(d.status, "pending"); + d.resolve(e); + assertEquals(d.status, "pending"); + e.resolve("🦕"); + assertEquals(await d, "🦕"); + assertEquals(d.status, "fulfilled"); });