Skip to content

Instantly share code, notes, and snippets.

@J-Cake
Last active October 16, 2021 08:12
Show Gist options
  • Save J-Cake/cacca78d357aa5c023fe744ec4e33cfd to your computer and use it in GitHub Desktop.
Save J-Cake/cacca78d357aa5c023fe744ec4e33cfd to your computer and use it in GitHub Desktop.
the `promisify` utility function converts a callback-style function to a promise-style one. It does this elegantly. Below is a generic TypeScript implementation
export function toPromise<ReturnType extends any[], ArgTypes extends any[]>(callbackFn: (...args: [...ArgTypes, (err: any, ...data: ReturnType) => void]) => void): (...args: ArgTypes) => Promise<ReturnType> {
return function (...args: ArgTypes): Promise<ReturnType> {
return new Promise(function (resolve) {
callbackFn(...args, (err: any, ...data: ReturnType) => resolve(data));
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment