Last active
December 16, 2015 14:19
-
-
Save gusaaaaa/5447368 to your computer and use it in GitHub Desktop.
Generates a sequence of thens
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
| // Requires https://github.com/tildeio/rsvp.js | |
| // Once in a blue moon we need to concatenate several thens executing basically the same code. | |
| // Example: | |
| // f().then(function(message) { | |
| // alert(message + " #1"); | |
| // return f(); | |
| // }).then(function(message) { | |
| // alert(message + " #2"); | |
| // return f(); | |
| // }).then(function(message) { | |
| // alert(message + " #3"); | |
| // return f(); | |
| // }).then(function(message) { | |
| // alert("last call"); | |
| // }, function(error) { // handle error }); | |
| // The following function let us compact the previous example, producing a sequence of thens sharing a common iterator. | |
| // Example: | |
| // f().sequence(1, 3, function(message, iter) { | |
| // alert(message + " #" + iter); | |
| // }).then(function() { | |
| // alert("last call"); | |
| // }, function(error) { // handle error }); | |
| RSVP.Promise.prototype.sequence = function(start, end, fulfilled) { | |
| var promise = this; | |
| var shared = {iter: start}; | |
| for (var j=start; j<=end; j++) { | |
| var wrapper = function() { | |
| var args = Array.prototype.slice.call(arguments); | |
| if (args.length == 1 && 'undefined' == typeof(args[0])) { args = [] }; | |
| var i = this.iter; | |
| this.iter++; | |
| return fulfilled.apply(this, args.concat(i)); | |
| } | |
| promise = promise.then(wrapper.bind(shared)); | |
| } | |
| return promise; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment