Last active
August 29, 2015 14:02
-
-
Save datchley/2fd6996e27ce1e9954ad to your computer and use it in GitHub Desktop.
Simple Promise/Deferred library (likely not Promise/A+ aligned).
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
| var Promise = function() { | |
| this.resolve_callbacks = []; | |
| this.reject_callbacks = []; | |
| this.state = null; | |
| }; | |
| Promise.prototype = { | |
| then: function(resolvefn, rejectfn) { | |
| if (this.state == 'resolved') { | |
| resolvefn(); | |
| return this; | |
| } | |
| if (this.state == 'rejected') { | |
| rejectfn(); | |
| return this; | |
| } | |
| this.resolve_callbacks.push(resolvefn); | |
| if (rejectfn) { | |
| this.reject_callbacks.push(rejectfn); | |
| } | |
| return this; | |
| } | |
| }; | |
| var Defer = function() { | |
| this.promise = new Promise(); | |
| }; | |
| Defer.prototype = { | |
| resolve: function (data) { | |
| this.promise.resolve_callbacks.forEach(function(callback) { | |
| window.setTimeout(function () { | |
| callback(data); | |
| }, 0); | |
| }); | |
| this.promise.state = 'resolved'; | |
| return this.promise; | |
| }, | |
| reject: function (error) { | |
| this.promise.reject_callbacks.forEach(function(callback) { | |
| window.setTimeout(function () { | |
| callback(error); | |
| }, 0); | |
| }); | |
| this.promise.state = 'rejected'; | |
| return this.promise; | |
| } | |
| }; | |
| var when = function() { | |
| var deferreds = [].slice.call(arguments), | |
| len = deferreds.length, | |
| defer = new Defer(), | |
| done = 0; | |
| for (var i=0; i < len; i++) { | |
| deferreds[i].call(null).then(function() { | |
| if (++done == len) { | |
| defer.resolve(); | |
| } | |
| }); | |
| } | |
| return defer.promise; | |
| }; | |
| // | |
| // UNIT TEST | |
| // | |
| // A & B immediately resolve (synchronous) | |
| function A() { | |
| var defer = new Defer(); | |
| console.log("A() called. context: %o", this); | |
| return defer.resolve(); | |
| } | |
| function B() { | |
| var defer = new Defer(); | |
| console.log("B() called. context: %o", this); | |
| return defer.resolve(); | |
| } | |
| // C resolves asynchronously, returning the promise. | |
| function C() { | |
| var _this = this, | |
| defer = new Defer(); | |
| setTimeout(function() { | |
| console.log("C() called. context: %o", _this); | |
| defer.resolve(); | |
| }, 3000); | |
| return defer.promise; | |
| } | |
| // Simple promise, then chain | |
| A().then(B); | |
| // wrapping promises in groups | |
| when(A,B).then(C); | |
| // complex then chain | |
| C() | |
| .then(B) | |
| .then(A) | |
| .then(function(data) { | |
| console.log("This chain is clean!"); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment