limit-concur

Limit an async function's concurrency with ease!

Usage no npm install needed!

<script type="module">
  import limitConcur from 'https://cdn.skypack.dev/limit-concur';
</script>

README

limit-concur

Limit an async function's concurrency with ease!

Install

$ npm i limit-concur

Usage

import got from 'got'
import limitConcur from 'limit-concur'

const categories = await got(
  `https://api.chucknorris.io/jokes/categories`,
).json()

async function getChuckNorrisJoke(category) {
  const { value } = await got(`https://api.chucknorris.io/jokes/random`, {
    searchParams: {
      category,
    },
  }).json()
  return value
}

const limitedGetChuckNorrisJoke = limitConcur(4, getChuckNorrisJoke)

// At most 4 requests are pending at any given time!
const jokes = await Promise.all(categories.map(limitedGetChuckNorrisJoke))
console.log(jokes)
//=> [
//     'Chuck Norris once rode a nine foot grizzly bear through an automatic car wash, instead of taking a shower.',
//     "Chuck Norris is actually the front man for Apple. He let's Steve Jobs run the show when he's on a mission. Chuck Norris is always on a mission.",
//     "Bill Gates thinks he's Chuck Norris. Chuck Norris actually laughed. Once.",
//     'Chuck Norris can install iTunes without installing Quicktime.',
//     ...
//   ]

You can get an API equivalent to p-limit like so:

import limitConcur from 'limit-concur'

const limit = limitConcur(1, fn => fn())

const input = [
  limit(() => fetchSomething(`foo`)),
  limit(() => fetchSomething(`bar`)),
  limit(() => doSomething()),
]

const result = await Promise.all(input)
console.log(result)
//=> [ ..., ..., ... ]

Contributing

Stars are always welcome!

For bugs and feature requests, please create an issue.

For pull requests, please read the contributing guidelines.

License

Apache 2.0

This is not an official Google product.