Limit an async function's concurrency with ease!
$ npm i limit-concur
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)
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)
//=> [ ..., ..., ... ]
Stars are always welcome!
For bugs and feature requests, please create an issue.