diff options
author | Samy Pessé <samypesse@gmail.com> | 2015-02-13 00:04:27 +0100 |
---|---|---|
committer | Samy Pessé <samypesse@gmail.com> | 2015-02-13 00:04:27 +0100 |
commit | 7c8386986919f611dcdaaf917bf0c24fabcfe3a4 (patch) | |
tree | d73e830143ab6bc60721d489cb9ff947e3f21ba0 /lib/utils | |
parent | 57d5c23eafbce5dc3b5351a4a5a6520434c717fd (diff) | |
download | gitbook-7c8386986919f611dcdaaf917bf0c24fabcfe3a4.zip gitbook-7c8386986919f611dcdaaf917bf0c24fabcfe3a4.tar.gz gitbook-7c8386986919f611dcdaaf917bf0c24fabcfe3a4.tar.bz2 |
Limit concurrent blocks processed
Diffstat (limited to 'lib/utils')
-rw-r--r-- | lib/utils/batch.js | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/lib/utils/batch.js b/lib/utils/batch.js new file mode 100644 index 0000000..5b92be5 --- /dev/null +++ b/lib/utils/batch.js @@ -0,0 +1,51 @@ +var Q = require("q"); +var _ = require("lodash"); + +// Execute a method for all element +function execEach(items, options) { + var concurrents = 0, d = Q.defer(), pending = []; + + options = _.defaults(options || {}, { + max: 100, + fn: function(item) {} + }); + + + function startItem(item, i) { + if (concurrents >= options.max) { + pending.push([item, i]); + return; + } + + concurrents++; + Q() + .then(function() { + return options.fn(item, i); + }) + .then(function() { + concurrents--; + + // Next pending + var next = pending.shift(); + + if (concurrents == 0 && !next) { + d.resolve(); + } else if (next) { + startItem.apply(null, next); + } + }) + .fail(function(err) { + pending = []; + d.reject(err); + }) + } + + _.each(items, startItem); + + return d.promise; +} + +module.exports = { + execEach: execEach +}; + |