Created
February 22, 2019 16:41
-
-
Save crazy4groovy/a258c0d8be103e083ad81c4e034a3268 to your computer and use it in GitHub Desktop.
How to throttle an array of promises until they've resolved
This file contains 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
const delay = | |
(ms) => // HOF, aka "constructor" providing state | |
() => // <<-- the thunk, executes a promise // | |
new Promise( | |
(resolve) => { | |
console.log('start work for >>', ms, 'ms') | |
setTimeout(resolve, ms, ms) | |
} | |
) | |
let line = 0 | |
const logger = async (...args) => console.log(line++, ':', ...args) | |
// instantiate new Array<thunk> | |
const resetThunks = () => [ | |
delay(1000), | |
delay(100), | |
delay(2000), | |
delay(500), | |
] | |
async function main() { | |
/////// SYNC all confirm | |
let thunks = resetThunks() | |
await thunks.reduce( // returns final Promise | |
async (prevPromise, currThunk) => { | |
await prevPromise | |
return currThunk().then(logger) | |
}, | |
Promise.resolve()) | |
logger('!!!!!!! reduce DONE\n') | |
/////// ASYNC, all confirm | |
thunks = resetThunks() | |
await Promise.all( | |
thunks.map( // returns an Array<Promise> | |
currThunk => currThunk().then(logger) | |
)) | |
logger('!!!!!!! all map DONE\n') | |
////// ASYNC, fastest confirm | |
thunks = resetThunks() | |
await Promise.race( | |
thunks.map( // returns an Array<Promise> | |
currThunk => currThunk().then(logger) | |
)) | |
logger('!!!!!!! race map DONE\n') | |
logger('MORE WORK... lalala\n\n\n') | |
} | |
main() | |
'MAIN IS DONE' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment