Skip to content

Instantly share code, notes, and snippets.

@felixSchl
Last active November 4, 2016 19:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felixSchl/8955008908385033e369 to your computer and use it in GitHub Desktop.
Save felixSchl/8955008908385033e369 to your computer and use it in GitHub Desktop.
chunked promise
var Promise = require('bluebird')
, _ = require('lodash')
;
var xs = [ 1, 2, 3, 4 ];
var mapLimit = function(xs, limit, f) {
return Promise.all(_.foldl(
_.chunk(xs, limit)
, function(acc, chunk) {
return acc.then(function() {
return Promise.all(
_.map(chunk, function(val) { return f(val); })
);
})
}
, new Promise(function(resolve, reject) { resolve(); })
));
};
mapLimit(
xs
, 200
, function(val) {
console.log("Returning promise for", val);
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("Resolved", val);
resolve(val);
}, 1000);
});
}
)
.then(function() { console.log("DONE!"); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment