Created
December 18, 2017 14:42
-
-
Save funny-falcon/ad6f5e6b1a76b8e4ccc1ab3befa7a5c7 to your computer and use it in GitHub Desktop.
Promise proxy
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
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) | |
} |
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
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