Skip to content

Instantly share code, notes, and snippets.

@GitaiQAQ
Last active May 25, 2023 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GitaiQAQ/d3b95902fe82ebd016cb99de9400983d to your computer and use it in GitHub Desktop.
Save GitaiQAQ/d3b95902fe82ebd016cb99de9400983d to your computer and use it in GitHub Desktop.
export function createPendingValue<T, Ref = any, S = never>(ref: Ref, key: keyof Ref) {
let resolve!: (v: T) => void;
let reject!: (reason?: any) => void;
const p = new Promise<T>((_resolve, _reject) => {
resolve = value => {
ref[key] = value as Ref[keyof Ref];
_resolve(value);
};
reject = reason => {
ref[key] = createPendingValue<T, Ref, S>(ref, key) as Ref[keyof Ref];
_reject(reason);
};
});
const assigned = Object.assign(p, { resolve, reject, isPending: true } as const);
return p as (typeof assigned & S) | (T & { isPending?: false });
}
export type PendingValue<T, Ref, S> = ReturnType<typeof createPendingValue<T, Ref, S>>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment