Skip to content

Instantly share code, notes, and snippets.

@trim21
Created April 12, 2023 07:39
Show Gist options
  • Save trim21/923cb4a81730146a1d81e4995e9e14a4 to your computer and use it in GitHub Desktop.
Save trim21/923cb4a81730146a1d81e4995e9e14a4 to your computer and use it in GitHub Desktop.
typescript callback/promise style async function
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