Skip to content

Instantly share code, notes, and snippets.

@creationix
Created November 20, 2009 16:41
Show Gist options
  • Save creationix/239608 to your computer and use it in GitHub Desktop.
Save creationix/239608 to your computer and use it in GitHub Desktop.
Simple re-implementation of Dojo's Deferred constructor
function Deferred() {
this.chain = [];
}
Deferred.prototype.addBoth = function (cb) {
this.chain.push([cb, cb]);
return this;
}
Deferred.prototype.addCallback = function (cb) {
this.chain.push([cb, null]);
return this;
}
Deferred.prototype.addCallbacks = function (cb, eb) {
this.chain.push([cb, eb]);
return this;
}
Deferred.prototype.addErrback = function (eb) {
this.chain.push([null, eb]);
return this;
}
Deferred.prototype.callback = function (res) {
this.chain.forEach(function (pair) {
if (pair[0] !== null) {
res = pair[0](res);
}
});
return res;
}
Deferred.prototype.errback = function (res) {
this.chain.forEach(function (pair) {
if (pair[1] !== null) {
res = pair[1](res);
}
});
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment