promise-parallel-throttle
Version:
Run promises in parallel, but throttled
3 lines (2 loc) • 1.98 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).throttle={})}(this,(function(e){"use strict";var t={maxInProgress:5,failFast:!1,nextCheck:function(e,t){return Promise.resolve(e.amountStarted<t.length)},ignoreIsFunctionCheck:!1};function n(e,n){return new Promise((function(s,o){var u=Object.assign({},t,n),r={lastCompletedIndex:-1,amountDone:0,amountStarted:0,amountResolved:0,amountRejected:0,amountNextCheckFalsey:0,rejectedIndexes:[],resolvedIndexes:[],nextCheckFalseyIndexes:[],taskResults:[]};if(0===e.length)return s(r);for(var a=!1,i=0,c=function(e,t){if(r.taskResults[t]=e,r.rejectedIndexes.push(t),r.amountRejected++,!0===u.failFast)return r.lastCompletedIndex=t,a=!0,o(r);f(t)},f=function(t){if(!0!==a){if(r.amountDone++,r.lastCompletedIndex=t,"function"==typeof u.progressCallback&&u.progressCallback(r),r.amountDone===e.length)return s(r);i<e.length&&l(i++)}},l=function(t){u.nextCheck(r,e).then((function(n){!0===n?function(t){if(r.amountStarted++,"function"==typeof e[t])try{e[t]().then((function(e){r.taskResults[t]=e,r.resolvedIndexes.push(t),r.amountResolved++,f(t)}),(function(e){c(e,t)}))}catch(e){c(e,t)}else{if(!0!==u.ignoreIsFunctionCheck)return a=!0,o(new Error("tasks["+t+"]: "+e[t]+", is supposed to be of type function"));r.taskResults[t]=e[t],r.resolvedIndexes.push(t),r.amountResolved++,f(t)}}(t):(r.amountNextCheckFalsey++,r.nextCheckFalseyIndexes.push(t),f(t))}),o)},d=0;d<Math.min(u.maxInProgress,e.length);d++)l(i++)}))}function s(e,t){return new Promise((function(s,o){n(e,t).then((function(e){s(e.taskResults)}),(function(e){e instanceof Error?o(e):o(e.taskResults[e.rejectedIndexes[0]])}))}))}e.all=function(e,t){return s(e,Object.assign({},{failFast:!0},t))},e.raw=n,e.sync=function(e,t){return s(e,Object.assign({},{maxInProgress:1,failFast:!0},t))}}));
//# sourceMappingURL=throttle.js.map