Skip to content

Instantly share code, notes, and snippets.

@znck
Last active August 14, 2019 15:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save znck/bb5717d158915af6822f43a56e86d52d to your computer and use it in GitHub Desktop.
Save znck/bb5717d158915af6822f43a56e86d52d to your computer and use it in GitHub Desktop.
Moved to https://github.com/znck/promised | A utility to convert callbacks to promises.
import {promisify, CustomPromisify} from 'util'
export type FunctionProxy<T extends Function> = CustomPromisify<T>
export type PackageProxy<P extends { [key: string]: Function }> = {
[K in keyof P]: FunctionProxy<P[K]>
}
export function promised<T extends { [key: string]: Function | any }>(target: T): PackageProxy<T> {
return new Proxy(target, {
get(target: T, key: string): any {
const value: any = target[key]
if (typeof value === 'function') {
return promisedFunction(value)
}
return value
}
})
}
function promisedFunction<T extends Function>(fn: T): CustomPromisify<T> | T {
return new Proxy(fn, {
apply(target, _this, args) {
if (target.length > args.length) {
return promisify(fn).apply(_this, args)
}
return fn.apply(_this, args)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment