Skip to content

Instantly share code, notes, and snippets.

@icodeforlove
Last active December 11, 2015 22:29
Show Gist options
  • Select an option

  • Save icodeforlove/4669939 to your computer and use it in GitHub Desktop.

Select an option

Save icodeforlove/4669939 to your computer and use it in GitHub Desktop.
add a few features kind of like async's forEachLimit but for what.js
// example:
//
// var promises = new PromiseStack();
//
// for (var i = 0; i < 10; i++) promises.push(/* a promise */, /* args... */);
//
// promises.limit(
// 4,
// function () {
// console.log('success');
// },
// function (error) {
// console.log(error.message);
// }
// );
function PromiseStack () {
this._calls = [];
}
PromiseStack.prototype = {
push: function (func) {
var args = Array.prototype.slice.call(arguments).slice(1);
this._calls.push([func, args]);
},
series: function (callback, error) {
var firstCall = this._calls.shift(),
deferred = firstCall[0].apply(null, firstCall[1]);
this._calls.forEach(function (call) {
deferred = deferred.then(function () {
return call[0].apply(null, call[1]);
});
});
deferred.then(callback, error);
return deferred;
},
limit: function (limit, callback, errorCallback) {
var calls = this._calls,
errored = false;
function error (message) {
errorCallback(errored = message);
}
function next () {
if (errored) return;
var call = calls.shift();
call[0].apply(null, call[1]).then(calls.length ? next : callback, error);
}
for (var i = 0; i < limit; i++) next();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment