p-limit vs async vs bottleneck vs promise-limit vs rate-limiter-flexible
비동기 처리 라이브러리
p-limitasyncbottleneckpromise-limitrate-limiter-flexible유사 패키지:

비동기 처리 라이브러리

비동기 처리 라이브러리는 JavaScript에서 비동기 작업을 효율적으로 관리하고 제어하기 위해 사용됩니다. 이러한 라이브러리는 비동기 함수의 실행을 조정하고, 병렬 처리의 수를 제한하며, 작업의 속도를 조절하는 데 도움을 줍니다. 이로 인해 성능을 최적화하고, 서버에 대한 부하를 줄이며, 사용자 경험을 향상시킬 수 있습니다.

npm 다운로드 트렌드

3 년

GitHub Stars 순위

통계 세부사항

패키지
다운로드
Stars
크기
Issues
발행일
라이선스
p-limit461,131,1332,94316.1 kB02ヶ月前MIT
async146,162,03728,120808 kB472年前MIT
bottleneck15,603,3862,009-897年前MIT
promise-limit9,522,898142-108年前ISC
rate-limiter-flexible4,759,0733,605234 kB124日前ISC

기능 비교: p-limit vs async vs bottleneck vs promise-limit vs rate-limiter-flexible

비동기 제어 흐름

  • p-limit:

    p-limit는 동시 실행할 비동기 작업의 수를 제한합니다. 이를 통해 서버에 대한 부하를 줄이고, 성능을 최적화할 수 있습니다.

  • async:

    async는 비동기 작업을 위한 다양한 제어 흐름을 제공합니다. 콜백, 프로미스, 제너레이터를 지원하여 복잡한 비동기 로직을 간단하게 구현할 수 있습니다.

  • bottleneck:

    bottleneck은 비동기 작업의 실행 속도를 조절하는 데 특화되어 있습니다. 작업을 대기열에 넣고, 설정한 속도에 따라 순차적으로 실행할 수 있습니다.

  • promise-limit:

    promise-limit은 비동기 작업의 수를 제한하고, 각 작업이 완료될 때까지 대기하도록 합니다. 이를 통해 작업의 흐름을 제어할 수 있습니다.

  • rate-limiter-flexible:

    rate-limiter-flexible는 API 호출이나 데이터베이스 쿼리의 속도를 조절하는 데 유용합니다. 다양한 제한 규칙을 설정하여 유연한 속도 조절이 가능합니다.

사용 사례

  • p-limit:

    p-limit는 동시 실행할 수 있는 비동기 작업의 수를 제한해야 할 때 사용됩니다. 예를 들어, 대량의 파일을 동시에 처리할 때 유용합니다.

  • async:

    async는 복잡한 비동기 로직을 처리할 때 유용합니다. 예를 들어, 여러 API 호출을 순차적으로 실행하거나, 비동기 작업의 결과를 조합할 때 사용됩니다.

  • bottleneck:

    bottleneck은 API 호출의 속도를 제한해야 할 때 적합합니다. 예를 들어, 초당 호출 수를 제한하여 서버의 부하를 줄이는 데 유용합니다.

  • promise-limit:

    promise-limit은 비동기 작업의 수를 제한하고, 각 작업이 완료될 때까지 대기해야 할 때 유용합니다. 예를 들어, 데이터베이스에 대한 쿼리를 순차적으로 실행할 때 사용됩니다.

  • rate-limiter-flexible:

    rate-limiter-flexible는 API 호출의 속도를 조절해야 할 때 유용합니다. 예를 들어, 특정 시간 내에 호출 수를 제한하여 서버의 안정성을 높일 수 있습니다.

설계 원칙

  • p-limit:

    p-limit는 간단한 API를 제공하여 사용자가 쉽게 동시 실행 수를 조절할 수 있도록 설계되었습니다.

  • async:

    async는 비동기 작업을 간단하게 관리할 수 있도록 설계되었습니다. 콜백 지옥을 피하고, 코드의 가독성을 높이는 데 중점을 두고 있습니다.

  • bottleneck:

    bottleneck은 작업의 실행 속도를 조절하는 데 중점을 두고 설계되었습니다. 대기열을 관리하여 작업의 흐름을 원활하게 유지합니다.

  • promise-limit:

    promise-limit은 Promise 기반의 비동기 작업을 관리할 수 있도록 설계되었습니다. 각 작업이 완료될 때까지 대기하는 방식으로 흐름을 제어합니다.

  • rate-limiter-flexible:

    rate-limiter-flexible는 다양한 제한 규칙을 설정할 수 있도록 설계되어, 유연한 속도 조절이 가능합니다.

유지보수

  • p-limit:

    p-limit는 간단한 구조로 유지보수가 용이하며, 사용하기 쉬운 API를 제공합니다.

  • async:

    async는 널리 사용되는 라이브러리로, 활발한 커뮤니티와 문서가 제공되어 유지보수가 용이합니다.

  • bottleneck:

    bottleneck은 명확한 API와 문서로 유지보수가 쉽습니다. 또한, 성능 최적화에 대한 다양한 팁이 제공됩니다.

  • promise-limit:

    promise-limit은 간단한 사용법으로 유지보수가 쉽고, 코드의 가독성을 높이는 데 기여합니다.

  • rate-limiter-flexible:

    rate-limiter-flexible는 다양한 설정 옵션을 제공하여 유지보수가 용이하며, 문서화가 잘 되어 있습니다.

학습 곡선

  • p-limit:

    p-limit는 간단한 API로 인해 학습 곡선이 낮습니다. 쉽게 이해하고 사용할 수 있습니다.

  • async:

    async는 다양한 비동기 패턴을 지원하지만, 초보자에게는 다소 복잡할 수 있습니다. 그러나 기본적인 사용법은 직관적입니다.

  • bottleneck:

    bottleneck은 사용하기 쉬운 API를 제공하여 학습 곡선이 낮습니다. 기본적인 사용법을 익히는 데 큰 어려움이 없습니다.

  • promise-limit:

    promise-limit은 Promise 기반의 비동기 작업을 관리하는 데 초점을 맞추고 있어, 기본적인 사용법이 직관적입니다.

  • rate-limiter-flexible:

    rate-limiter-flexible는 다양한 설정이 가능하지만, 기본적인 사용법은 비교적 간단하여 학습 곡선이 낮습니다.

선택 방법: p-limit vs async vs bottleneck vs promise-limit vs rate-limiter-flexible

  • p-limit:

    동시 실행할 비동기 작업의 수를 제한하고 싶다면 p-limit를 선택하세요. 이 패키지는 프로미스를 기반으로 하며, 간단한 API로 동시 실행 수를 조절할 수 있습니다.

  • async:

    비동기 작업을 간단하게 관리하고 싶다면 async를 선택하세요. 다양한 비동기 제어 흐름을 제공하며, 콜백 기반의 코드에서 프로미스 기반으로 쉽게 전환할 수 있습니다.

  • bottleneck:

    비동기 작업의 실행 속도를 조절하고 싶다면 bottleneck을 선택하세요. 이 패키지는 작업의 실행 속도를 제한하고, 대기열을 관리하는 데 유용합니다.

  • promise-limit:

    비동기 작업의 수를 제한하고, 각 작업이 완료될 때까지 대기하도록 하고 싶다면 promise-limit을 선택하세요. 이 패키지는 Promise를 기반으로 하여 작업의 흐름을 제어합니다.

  • rate-limiter-flexible:

    API 호출이나 데이터베이스 쿼리의 속도를 조절하고 싶다면 rate-limiter-flexible를 선택하세요. 이 패키지는 다양한 제한 규칙을 설정할 수 있어 유연한 속도 조절이 가능합니다.

p-limit의 README

p-limit

Run multiple promise-returning & async functions with limited concurrency

Works in Node.js and browsers.

Install

npm install p-limit

Usage

import pLimit from 'p-limit';

const limit = pLimit(1);

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

// Only one promise is run at once
const result = await Promise.all(input);
console.log(result);

API

pLimit(concurrency) default export

Returns a limit function.

concurrency

Type: number | object
Minimum: 1

Concurrency limit.

You can pass a number or an options object with a concurrency property.

rejectOnClear

Type: boolean
Default: false

Reject pending promises with an AbortError when clearQueue() is called. This is recommended if you await the returned promises, for example with Promise.all, so pending tasks do not remain unresolved after clearQueue().

import pLimit from 'p-limit';

const limit = pLimit({concurrency: 1});

limit(fn, ...args)

Returns the promise returned by calling fn(...args).

fn

Type: Function

Promise-returning/async function.

args

Any arguments to pass through to fn.

Support for passing arguments on to the fn is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions.

Warning: Avoid calling the same limit function inside a function that is already limited by it. This can create a deadlock where inner tasks never run. Use a separate limiter for inner tasks.

limit.map(iterable, mapperFunction)

Process an iterable of inputs with limited concurrency.

The mapper function receives the item value and its index.

Returns a promise equivalent to Promise.all(Array.from(iterable, (item, index) => limit(mapperFunction, item, index))).

If the iterable throws during iteration, the returned promise rejects with that error. Mapper functions that were already scheduled still run, and their results are discarded.

This is a convenience function for processing inputs that arrive in batches. For more complex use cases, see p-map.

limit.activeCount

The number of promises that are currently running.

limit.pendingCount

The number of promises that are waiting to run (i.e. their internal fn was not called yet).

limit.clearQueue()

Discard pending promises that are waiting to run.

This might be useful if you want to tear down the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app.

Note: This does not cancel promises that are already running.

When rejectOnClear is enabled, pending promises are rejected with an AbortError. This is recommended if you await the returned promises, for example with Promise.all, so pending tasks do not remain unresolved after clearQueue().

limit.concurrency

Get or set the concurrency limit.

limitFunction(fn, options) named export

Returns a function with limited concurrency.

The returned function manages its own concurrent executions, allowing you to call it multiple times without exceeding the specified concurrency limit.

Ideal for scenarios where you need to control the number of simultaneous executions of a single function, rather than managing concurrency across multiple functions.

import {limitFunction} from 'p-limit';

const limitedFunction = limitFunction(async () => {
	return doSomething();
}, {concurrency: 1});

const input = Array.from({length: 10}, limitedFunction);

// Only one promise is run at once.
await Promise.all(input);

fn

Type: Function

Promise-returning/async function.

options

Type: object

concurrency

Type: number
Minimum: 1

Concurrency limit.

rejectOnClear

Type: boolean
Default: false

Reject pending promises with an AbortError when clearQueue() is called. This is recommended if you await the returned promises, for example with Promise.all, so pending tasks do not remain unresolved after clearQueue().

limitedFunction.clearQueue()

Discard pending calls that have not started yet.

When rejectOnClear is enabled, pending promises are rejected with an AbortError. Otherwise, their promises remain unresolved.

This does not cancel calls that are already running.

Recipes

See recipes.md for common use cases and patterns.

FAQ

How is this different from the p-queue package?

This package is only about limiting the number of concurrent executions, while p-queue is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue.

Related

  • p-throttle - Throttle promise-returning & async functions
  • p-debounce - Debounce promise-returning & async functions
  • p-map - Run promise-returning & async functions concurrently with different inputs
  • p-all - Run promise-returning & async functions concurrently with optional limited concurrency
  • More…