Skip to content

Instantly share code, notes, and snippets.

@scwood
Created May 2, 2022 20:26
Show Gist options
  • Save scwood/b6f83527006a4fe8a2b30a806397866a to your computer and use it in GitHub Desktop.
Save scwood/b6f83527006a4fe8a2b30a806397866a to your computer and use it in GitHub Desktop.
Strongly typed promisify utility function
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