Skip to content

Instantly share code, notes, and snippets.

@orion55
Created August 23, 2023 06:06
Show Gist options
  • Save orion55/4b663e6f47497ebec357736277966723 to your computer and use it in GitHub Desktop.
Save orion55/4b663e6f47497ebec357736277966723 to your computer and use it in GitHub Desktop.
promisifyAll
type CallbackBasedAsyncFunction<T> = (callback: (response: ApiResponse<T>) => void) => void;
type PromiseBasedAsyncFunction<T> = () => Promise<T>;
export function promisify<T>(fn: CallbackBasedAsyncFunction<T>): PromiseBasedAsyncFunction<T> {
return () => new Promise<T>((resolve, reject) => {
fn((response) => {
if (response.status === 'success') {
resolve(response.data);
} else {
reject(new Error(response.error));
}
});
});
}
type SourceObject<T> = {[K in keyof T]: CallbackBasedAsyncFunction<T[K]>};
type PromisifiedObject<T> = {[K in keyof T]: PromiseBasedAsyncFunction<T[K]>};
export function promisifyAll<T extends {[key: string]: any}>(obj: SourceObject<T>): PromisifiedObject<T> {
const result: Partial<PromisifiedObject<T>> = {};
for (const key of Object.keys(obj) as (keyof T)[]) {
result[key] = promisify(obj[key]);
}
return result as PromisifiedObject<T>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment