Skip to content

Instantly share code, notes, and snippets.

@tobius
Created March 1, 2018 14:22
Show Gist options
  • Save tobius/aeb725a31b6dc0f767c660e8d1f6d620 to your computer and use it in GitHub Desktop.
Save tobius/aeb725a31b6dc0f767c660e8d1f6d620 to your computer and use it in GitHub Desktop.
`async.mapLimit` as a `promise`
const Promise = require('bluebird');
/**
* Produce a new collection of values by asynchronously mapping each value in
* `collection` through the `iteratee` function, but running a maximum of
* `limit` operations at a time.
*
* __Inspired by `async.mapLimit`__
*
* @param {Array} collection
* @param {Integer} limit
* @param {Function} iteratee
* @return {Promise}
*/
function mapLimit(collection, limit, iteratee) {
let queued = [];
const promises = collection.map((item) => {
const someLimit = Math.max(0, queued.length - limit + 1);
const iterate = Promise.some(queued, someLimit)
.then(() => {
return iteratee(item);
});
queued.push(iterate);
return iterate;
});
return Promise.all(promises);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment