/** @type {Record>} */ export const cache: Record> = {}; export interface PromiseWithState extends Promise { getIsPending: () => boolean; } function isPromiseWithState(promise: Promise | PromiseWithState): promise is PromiseWithState { return promise['getIsPending'] !== undefined; } /** * This function allow you to modify a JS Promise by adding some status properties. * @template {any} T * @param {Promise|PromiseWithState} promise * @return {PromiseWithState} */ export function makePromiseState(promise: Promise | PromiseWithState): PromiseWithState { // Don't modify any promise that has been already modified. if (isPromiseWithState(promise)) { return promise; } // Set initial state let isPending = true; // Observe the promise, saving the fulfillment in a closure scope. let result = promise.then( (v) => { isPending = false; return v; }, (e) => { isPending = false; throw e; }, ) as PromiseWithState; result.getIsPending = function getIsPending() { return isPending; }; return result; }