Created
August 23, 2023 06:06
-
-
Save orion55/4b663e6f47497ebec357736277966723 to your computer and use it in GitHub Desktop.
promisifyAll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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