Created
April 12, 2023 07:39
-
-
Save trim21/923cb4a81730146a1d81e4995e9e14a4 to your computer and use it in GitHub Desktop.
typescript callback/promise style async function
This file contains 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 Callback<T = any> = (err?: unknown, result?: T) => void | |
export async function returnSomething(): Promise<number>; | |
export function returnSomething(callback: Callback<number>): void; | |
export function returnSomething(callback?: Callback<number>): void | Promise<number> { | |
return asCallback<number>(asyncCall(), callback) | |
} | |
async function asyncCall(): Promise<number> { | |
return Promise.resolve(1) | |
} | |
function asCallback<T>(promise: Promise<T>, cb?: (err?: unknown, result?: T) => void): Promise<T> | void { | |
if (cb === undefined) { | |
return promise | |
} | |
promise.then( | |
(result) => { | |
cb(null, result) | |
}, | |
(err) => { | |
cb(err) | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment