On Thursday, October 25, 2012 3:37:25 AM UTC+2, Jim Tittsler wrote:
> What is the best pattern for limiting the concurrency of resolving an
> array (queue) of promises? I'd like to have another argument to Q.all (or
> qq's queue?) that would allow at most a specified number of the functions
> being processed at once.
I solved it by using async and creating a queue that promises to give you a
callback to call when you're done.
Coffeescript:
Q = require 'q'
async = require 'async'
promisQue = async.queue(
(deferred, callback) ->
deferred.resolve(callback)
3
)
throttledPromise = () ->
deferred = Q.defer()
promisQue.push deferred
deferred.promise
for i in [1..50]
((i) ->
throttledPromise().then (cb) ->
setTimeout cb, 500
console.log i
)(i)
Javascript:
var Q, async, i, promisQue, throttledPromise, _fn, _i;
Q = require('q');
async = require('async');
promisQue = async.queue(function(deferred, callback) {
return deferred.resolve(callback);
}, 3);
throttledPromise = function() {
var deferred;
deferred = Q.defer();
promisQue.push(deferred);
return deferred.promise;
};
_fn = function(i) {
return throttledPromise().then(function(cb) {
setTimeout(cb, 500);
return console.log(i);
});
};
for (i = _i = 1; _i <= 50; i = ++_i) {
_fn(i);
}
Thoughts? (the anon (i) function is needed to keep a copy of i for the
promise)
Wout.