Skip to content

Instantly share code, notes, and snippets.

@ronaldronson
Created January 13, 2014 09:39
Show Gist options
  • Save ronaldronson/8397195 to your computer and use it in GitHub Desktop.
Save ronaldronson/8397195 to your computer and use it in GitHub Desktop.
Dummy promise
var Promise = (function () {
"use strict";
function worker(queue, val) {
return queue.reduce(function (res, obj, i) {
try {
return obj.fn(res);
} catch (ex) {
return obj.err(ex);
}
}, val);
}
function Promise() {
this.res = null;
this.queue = [];
}
Promise.prototype.when = function (fn) {
this.res = fn();
return this;
};
Promise.prototype.then = function (fn, err) {
this.queue.push({fn: fn, err: err});
return this;
};
Promise.prototype.done = function (fn, err) {
this.queue.push({fn: fn, err: err});
this.res = worker(this.queue, this.res);
return this.res;
};
return Promise;
}());
var promise = new Promise();
var res = promise.when(function () {
console.log("when " + 1);
return 1 + 1;
}).then(function (res) {
console.log("then " + res);
return Math.pow(res, res);
}, function (err) {
console.log("err " + err);
return 1;
}).done(function (res) {
console.log("done " + res);
return res * 4;
}, function (err) {
console.log("err " + err);
return 15;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment