Skip to content

Instantly share code, notes, and snippets.

@eduardolundgren
Created March 26, 2014 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eduardolundgren/9795138 to your computer and use it in GitHub Desktop.
Save eduardolundgren/9795138 to your computer and use it in GitHub Desktop.
CancellablePromise.sequence = function(values) {
var children = [];
return new A.CancellablePromise(
function(resolve, reject) {
if (!A.Lang.isArray(values)) {
reject(new TypeError('CancellablePromise.sequence expects an array of values or promises'));
return;
}
var instance = this,
child,
results = [],
remaining = values.length;
function resolveInternal(childPos, val) {
results[childPos-1] = val;
remaining--;
if (!remaining) {
resolve(results);
}
}
A.Array.each(values, function(maybePromise) {
child = A.CancellablePromise.resolve(maybePromise);
child = child.then(
A.rbind(resolveInternal, instance, children.push(child)),
A.bind(instance.cancel, instance));
});
},
function() {
A.Array.invoke(children, 'cancel');
children = null;
}
);
};
Y.CancellablePromise.sequence([
delay(100, 1),
delay(500, 2),
new Y.CancellablePromise(function (res, rej) { setTimeout(function() { rej(2.1); }, 600); }),
delay(1000, 3),
delay(2000, 4)
])
.then(function(data) {
console.log(data);
},
function(reason) {
console.log('rejected', reason);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment