Skip to content

Instantly share code, notes, and snippets.

@gusaaaaa
Last active December 16, 2015 14:19
Show Gist options
  • Select an option

  • Save gusaaaaa/5447368 to your computer and use it in GitHub Desktop.

Select an option

Save gusaaaaa/5447368 to your computer and use it in GitHub Desktop.
Generates a sequence of thens
// 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