Created
January 13, 2014 09:39
-
-
Save ronaldronson/8397195 to your computer and use it in GitHub Desktop.
Dummy promise
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
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