Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Created February 22, 2019 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crazy4groovy/a258c0d8be103e083ad81c4e034a3268 to your computer and use it in GitHub Desktop.
Save crazy4groovy/a258c0d8be103e083ad81c4e034a3268 to your computer and use it in GitHub Desktop.
How to throttle an array of promises until they've resolved
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