Skip to content

Instantly share code, notes, and snippets.

@pianosnake
Created August 22, 2017 21:13
Show Gist options
  • Save pianosnake/b8f453e9420ef0003f4c7b5cc0201f85 to your computer and use it in GitHub Desktop.
Save pianosnake/b8f453e9420ef0003f4c7b5cc0201f85 to your computer and use it in GitHub Desktop.
Promise throttling using a generator
function throttlePromises(elements, asyncForEach, groupSize){
return new Promise(function(resolve, reject){
//create a generator object that 'yields' for every group
const genObj = function* gen(){
while(elements.length > 0){
yield Promise.all(elements.splice(0, groupSize).map(asyncForEach))
.then(() => genObj.next());
}
return resolve(true);
}();
genObj.next();
})
}
//example
const concurrentRequests = 2;
const divIds = ['dog', 'cat', 'donkey', 'pig', 'chicken', 'coatimundi'];
const loadImage = function(x){
//dome something async with x
return load(x.jpg);
}
throttlePromises(divIds, loadImage, concurrentRequests);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment