Skip to content

Instantly share code, notes, and snippets.

@juandopazo
Forked from eduardolundgren/CancellablePromise.js
Last active August 29, 2015 13:57
Show Gist options
  • Save juandopazo/9785841 to your computer and use it in GitHub Desktop.
Save juandopazo/9785841 to your computer and use it in GitHub Desktop.
CancellablePromise.all = function (values) {
var CancellablePromise = this;
var child;
var children = [];
return new CancellablePromise(function (resolve, reject) {
if (!A.Lang.isArray(values)) {
reject(new TypeError('CancellablePromise.all expects an array of values or promises'));
return;
}
var remaining = values.length,
i = 0,
length = values.length,
results = [];
function oneDone(index) {
return function (value) {
results[index] = value;
remaining--;
if (!remaining) {
resolve(results);
}
};
}
if (length < 1) {
return resolve(results);
}
for (; i < length; i++) {
child = CancellablePromise.resolve(values[i]);
child.then(oneDone(i), reject);
children.push(child);
}
}, function () {
children.forEach(function (child) {
child.cancel();
});
}).then(function(result) {
console.log('CancellablePromise resolved');
return result;
},
function(reason) {
console.log('CancellablePromise rejected', children);
throw reason;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment