Created
March 1, 2018 14:22
-
-
Save tobius/aeb725a31b6dc0f767c660e8d1f6d620 to your computer and use it in GitHub Desktop.
`async.mapLimit` as a `promise`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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