Created
May 2, 2022 20:26
-
-
Save scwood/b6f83527006a4fe8a2b30a806397866a to your computer and use it in GitHub Desktop.
Strongly typed promisify utility 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 ErrorFirstCallback<D> = (error: any, data: D) => void; | |
type FunctionThatAcceptsCallback<A extends any[], D> = ( | |
...args: [...A, ErrorFirstCallback<D>] | |
) => void; | |
type FunctionThatReturnsPromise<A extends any[], D> = (...args: A) => Promise<D> | |
function promisify<A extends any[], D>( | |
originalFunction: FunctionThatAcceptsCallback<A, D> | |
): FunctionThatReturnsPromise<A, D> { | |
return (...args: A) => { | |
return new Promise((resolve, reject) => { | |
originalFunction(...args, (error, data) => { | |
if (error) { | |
reject(error); | |
} else { | |
resolve(data); | |
} | |
}); | |
}); | |
}; | |
} | |
function readFile( | |
path: string, | |
callback: (error: Error | null, fileContents: string) => void | |
) { | |
callback(null, "Fake file data"); | |
} | |
const readFilePromiseVersion = promisify(readFile); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment