limit-concur
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

limit-concur

Limit an async function's concurrency with ease!

Features

  • Wow: so amazing
  • Amazing: so wow
  • Fancy: has a tie and everything

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()

const getChuckNorrisJoke = async 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 License 2.0

This is not an official Google product.

Package Sidebar

Install

npm i limit-concur

Weekly Downloads

6

Version

2.0.0

License

Apache-2.0

Unpacked Size

16.4 kB

Total Files

6

Last publish

Collaborators

  • tomeraberbach