Last active
August 22, 2016 06:13
-
-
Save auser/ea582a2a853adb361fdc869967950279 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
* A small wrapper to turn a prototype, callback object | |
* to a chainable api using promises. | |
* | |
* Usage: | |
* var Klass = function() {} | |
* Klass.prototype.log = function(msg, cb) { | |
* console.log(msg); | |
* cb(); | |
* } | |
* | |
* chainWrapper(Klass); | |
*/ | |
const chainWrapper = function(klass) { | |
const promisify = function(fn) { | |
return function() { | |
return new Promise(function(resolve, reject) { | |
fn(function(err, res) { | |
return err ? reject(err) : resolve(res); | |
}); | |
}) | |
} | |
} | |
let next = new Promise(function(r) { r(); }) | |
const wrap = function(name) { | |
const oldFn = klass.prototype[name]; | |
klass.prototype[name] = function() { | |
next = next.then(promisify(oldFn)) | |
return this; | |
} | |
} | |
Object.keys(klass.prototype).forEach(wrap); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment