Skip to content

Instantly share code, notes, and snippets.

@spion

spion/maplimit.js

Created Apr 1, 2014
Embed
What would you like to do?
var Promise = require('bluebird');
function mapLimit(arr, n, f) {
var queued = [];
var results = arr.map(function(item) {
var mustComplete = Math.max(0, queued.length - n + 1);
var thisone = Promise.some(queued, mustComplete)
.thenReturn(item).then(f);
queued.push(thisone);
return thisone;
});
return Promise.all(results);
}
function test(val) {
console.log("Run", val);
return Promise.delay((8 - val) * 500)
.thenReturn(val * 2)
.tap(logResult);
}
function logResult(r) {
console.log("Result", r);
}
mapLimit([1,2,3,4,5,6,7], 3, test).then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment