denoland / std

The Deno Standard Library
https://jsr.io/@std
MIT License
3.22k stars 620 forks source link

suggestion: add `promiseState()` to `@std/async` #5727

Open PandaWorker opened 3 months ago

PandaWorker commented 3 months ago

Please add this utility to check the Promise status

export type PromiseState = 'fulfilled' | 'rejected' | 'pending';

var t = Symbol('t');

/**
 * Return state (fulfilled/rejected/pending) of a promise
 *
 * ```ts
 * import { assertEquals } from "@std/assert";
 * import { promiseState } from "@std/async/promise-state";
 *
 * assertEquals(await promiseState(Promise.resolve("value")), "fulfilled");
 * assertEquals(await promiseState(Promise.reject("error")), "rejected");
 * assertEquals(await promiseState(new Promise(() => {})), "pending");
 * ```
 */
export function promiseState(p: Promise<unknown>): Promise<PromiseState> {
    return Promise.race([p, t]).then(
        v => (v === t ? 'pending' : 'fulfilled'),
        () => 'rejected'
    );
}

export type PromiseStateOptions = {
    /**
     * If true, the promise state is checked immediately without waiting for the next event loop.
     */
    immediate?: boolean;
};

function flushPromises() {
    return new Promise<void>(resolve => setTimeout(resolve, 0));
}

export async function promiseState2(
    p: Promise<unknown>,
    { immediate }: PromiseStateOptions = {}
): Promise<PromiseState> {
    if (!immediate) await flushPromises();

    return Promise.race([p, t]).then(
        v => (v === t ? 'pending' : 'fulfilled'),
        () => 'rejected'
    );
}
iuioiua commented 3 months ago

Please provide a use case and reasons behind the suggestion.

PandaWorker commented 3 months ago

The native implementation of Promise does not provide the property "state", this implementation helps to get the current state of the promise

kt3k commented 3 months ago

Can you give us more practical example usages?

Other note: npm:promise-status-async seems providing a very similar API, but it has very few weekly downloads and github activities. I doubt there's much practical usages of it