Created
May 24, 2020 19:56
-
-
Save wraithgar/15b33dee641fb3b0265eafe34269a093 to your computer and use it in GitHub Desktop.
Promisify all the functions in any object with a few lines of es6
This file contains hidden or 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
const handler = { | |
get: function (target, prop, receiver) { | |
if (typeof target[prop] !== 'function' ) { | |
return target[prop] | |
} | |
return function () { | |
return new Promise((resolve, reject) => { | |
Reflect.get(target, prop, receiver).apply(target, [...arguments, function (err, result) { | |
if (err) { | |
return reject(err) | |
} | |
resolve(result) | |
}]) | |
}) | |
} | |
} | |
} | |
module.exports = function (thingToPromisify) { | |
return new Proxy(thingToPromisify, handler) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This has been turned into a real module with a little more complete feature set https://github.com/wraithgar/gar-promisify