Skip to content

Instantly share code, notes, and snippets.

@znck
Last active August 14, 2019 15:22
Show Gist options
  • 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