Skip to content

Instantly share code, notes, and snippets.

@funny-falcon
Created December 18, 2017 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save funny-falcon/ad6f5e6b1a76b8e4ccc1ab3befa7a5c7 to your computer and use it in GitHub Desktop.
Save funny-falcon/ad6f5e6b1a76b8e4ccc1ab3befa7a5c7 to your computer and use it in GitHub Desktop.
Promise proxy
let handlers = {}
handlers.get = function(target, property) {
let v = target[property]
if (typeof(v) == "function") {
return async (...args) => {
return new Promise((resolve, reject) => {
target[property](...args, (err, ...rest) => {
if (err) reject(err)
else resolve(rest.length == 1 ? rest[0] : rest)
})
})
}
} else {
return v
}
}
module.exports = function (obj) {
return new Proxy(obj, handlers)
}
let proxy = require('./promiseme')
let d = {}
d.x = 1
d.f = function (a, cb) {
let self = this;
setTimeout(function () { cb(null, self, a) }, 1000)
}
proxy(d).f("HELLO").then((x)=>{console.log(x)})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment