sindresorhus / p-limit

Run multiple promise-returning & async functions with limited concurrency
MIT License
1.84k stars 99 forks source link

Propose `limit.with` API to streamline `map()` usage #74

Open aaronccasanova opened 7 months ago

aaronccasanova commented 7 months ago

Hello, I'd like to propose introducing a limit.with API to streamline the process of creating limited functions with Array.prototype.map()

Current API:

const limit = pLimit(5)

// With inline function
await Promise.all(
  items.map(item => limit(async () => {
    await process(item)
  }))
)

// With function declaration
async function processItem(item) {
  await process(item)
}

await Promise.all(
  items.map(item => limit(() => processItem(item)))
)

Proposed API:

const limit = pLimit(5)

// With inline function
await Promise.all(
  items.map(limit.with(async item => {
    await process(item)
  }))
)

// With function declaration
async function processItem(item) {
  await process(item)
}

await Promise.all(
  items.map(limit.with(processItem))
)

While the difference is subtle, the intention is to remove some boilerplate and improve readability. I put together a POC here and am happy to follow up with documentation, any API/naming/etc changes, and opening a PR

septatrix commented 2 months ago

While it does not allow you to reuse the limiter across several places you could also find p-map interesting: https://github.com/sindresorhus/p-map