Last active
December 11, 2015 22:29
-
-
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
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
| // 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