Limit Q promise concurrency in Node js
I'd do this, which will iterate over each URL, building a chain of promises that run when the previous one finishes, and resolves with an array of the request results.
return urls.reduce(function(acc, url){
return acc.then(function(results)
return myfunction(url).then(function(requestResult){
return results.concat(requestResult)
});
});
}, Q.resolve([]));
You could turn that into a helper too:
var results = map(urls, myfunction);
function map(items, fn){
return items.reduce(function(acc, item){
return acc.then(function(results)
return fn(item).then(function(result){
return results.concat(result)
});
});
}, Q.resolve([])
}
Note, the bluebird
promise library has a helper to simplify this kind of thing.
return Bluebird.map(urls, myfunction, {concurrency: 1});