Created
July 9, 2016 15:14
-
-
Save loretoparisi/b02b0e40a4eeb2089e213481e245df1c to your computer and use it in GitHub Desktop.
Promise all in CoffeeScript
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
subset = [ | |
'item1' | |
'item2' | |
'item3' | |
] | |
# uniform distribution of wait times | |
waitTimes = arrayRangeMap(subset.length, -> | |
getRandomArbitrary(0.1, 0.3, 3) * 1000 | |
) | |
Q = PromiseAllP(subset, executionBlock, waitTimes) | |
getRandomArbitrary = (min, max, fixed) -> | |
fixed = fixed or 10 | |
(Math.random() * (max - min) + min).toFixed fixed | |
arrayRangeMap = (a, block) -> | |
c = [] | |
while a-- | |
c[a] = block() | |
c | |
Sleep = (time, block) -> | |
stop = (new Date).getTime() | |
while (new Date).getTime() < stop + time | |
continue | |
block() | |
return | |
PromiseAllP = (items, block, waitTimes) -> | |
promises = [] | |
index = 0 | |
items.forEach (item) -> | |
promises.push ((item, i) -> | |
new Promise((resolve, reject) -> | |
if waitTimes and i < waitTimes.length + 1 | |
Sleep waitTimes[i - 1], -> | |
block item, index, resolve, reject | |
else | |
block item, index, resolve, reject | |
return | |
) | |
)(item, ++index) | |
return | |
Promise.all promises | |
# execution on the item at index | |
executionBlock = (item, index, resolve, reject) -> | |
resolve index: item | |
Q.then (results) -> | |
console.log 'aggregated', results | |
return | |
Q.catch (error) -> | |
console.log error | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can try out this script here.