Skip to content

Instantly share code, notes, and snippets.

@tlivings
Created June 12, 2013 15:30
Show Gist options
  • Select an option

  • Save tlivings/5766358 to your computer and use it in GitHub Desktop.

Select an option

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.
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;
}
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