Created
June 12, 2013 15:30
-
-
Save tlivings/5766358 to your computer and use it in GitHub Desktop.
Object promisification. Playing with method mixin to build chain of callbacks and flatten. Not real promises yet.
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
| function Promisify(obj) { | |
| var original = Object.getPrototypeOf(obj); | |
| var Promise = function Promise() { | |
| this._chain = []; | |
| }; | |
| Promise.prototype = Object.create(Promise, { | |
| constructor : { | |
| value : original.constructor | |
| }, | |
| _push : { | |
| value : function(fn) { | |
| this._chain.push(fn); | |
| } | |
| }, | |
| then : { | |
| value : function(fn) { | |
| var cb = this._chain.shift(); | |
| return cb(fn.bind(promise)); | |
| } | |
| } | |
| }); | |
| Object.keys(original).forEach(function(key) { | |
| if(typeof original[key] === "function" && key !== "then") { | |
| Promise.prototype[key] = function() { | |
| var args = Array.prototype.slice.call(arguments); | |
| promise._push(function(fn) { | |
| args.push(fn); | |
| obj[key].apply(promise, args); | |
| return promise; | |
| }); | |
| return promise; | |
| }; | |
| } | |
| }); | |
| var promise = new Promise(); | |
| return promise; | |
| } |
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
| Promisify(obj) | |
| .hello("Joe") | |
| .then(function(message) { | |
| console.log(message); | |
| this.hello("Fred"); | |
| }) | |
| .then(function(message) { | |
| console.log(message); | |
| }) | |
| .goodbye("Joe") | |
| .then(function(message) { | |
| console.log(message); | |
| this.goodbye("Fred"); | |
| }) | |
| .then(function(message) { | |
| console.log(message); | |
| next(); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment