Created
August 22, 2017 21:13
-
-
Save pianosnake/b8f453e9420ef0003f4c7b5cc0201f85 to your computer and use it in GitHub Desktop.
Promise throttling using a generator
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
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