Skip to content

Instantly share code, notes, and snippets.

@kigiri
Created February 12, 2022 18:18
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 kigiri/71847e3a139798e701ca4ed98303b4d0 to your computer and use it in GitHub Desktop.
Save kigiri/71847e3a139798e701ca4ed98303b4d0 to your computer and use it in GitHub Desktop.
const allLimited = (actions, { delay = 0, concurrency = 1 }) =>
new Promise((s, f) => {
let i = -1
const end = actions.length
const result = Array(end)
const delayed = delay && (fn => setTimeout(fn, delay))
async function next(x) {
if (x >= end) return x - end >= concurrency && s(result)
try {
const pause = delay && new Promise(delayed)
result[x] = await actions[x]()
pause && (await pause)
next(++i)
} catch (err) {
f(err)
}
}
while (i < concurrency) next(++i)
})
@kigiri
Copy link
Author

kigiri commented Feb 12, 2022

You have 2 options:

  • concurrency limit how many actions are called in parallel
  • delay add a delay in ms between each call

Note that you must pass an array of functions, not an array of promises

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment