p-limit vs fastq
비동기 작업 제어 라이브러리
p-limitfastq유사 패키지:

비동기 작업 제어 라이브러리

비동기 작업 제어 라이브러리는 JavaScript에서 비동기 작업의 흐름을 관리하고 최적화하는 데 사용됩니다. 이러한 라이브러리는 비동기 함수의 실행을 제어하여 성능을 향상시키고, 리소스 사용을 최적화하며, 코드의 가독성을 높이는 데 도움을 줍니다. 'fastq'는 비동기 작업을 큐에 추가하고 병렬로 실행할 수 있도록 하며, 'p-limit'는 동시에 실행할 수 있는 비동기 작업의 수를 제한하여 리소스를 효율적으로 사용할 수 있게 합니다.

npm 다운로드 트렌드

3 년

GitHub Stars 순위

통계 세부사항

패키지
다운로드
Stars
크기
Issues
발행일
라이선스
p-limit444,814,0492,93916.1 kB02ヶ月前MIT
fastq187,440,6351,14150.6 kB252ヶ月前ISC

기능 비교: p-limit vs fastq

작업 큐 관리

  • p-limit:

    'p-limit'는 비동기 작업의 동시 실행 수를 제한하여 리소스 사용을 최적화합니다. 이로 인해 시스템이 과부하되지 않도록 하며, 안정적인 성능을 유지할 수 있습니다.

  • fastq:

    'fastq'는 비동기 작업을 큐에 추가하여 순차적으로 처리할 수 있도록 합니다. 이를 통해 작업의 흐름을 제어하고, 병렬로 실행할 수 있는 작업 수를 조정하여 성능을 극대화할 수 있습니다.

성능 최적화

  • p-limit:

    'p-limit'는 동시에 실행되는 작업 수를 제한하여, 시스템의 자원을 효율적으로 사용할 수 있게 합니다. 이는 특히 API 호출이나 데이터베이스 쿼리와 같이 리소스를 많이 소모하는 작업에서 유용합니다.

  • fastq:

    'fastq'는 비동기 작업을 병렬로 실행할 수 있어, 대량의 작업을 처리할 때 성능을 크게 향상시킬 수 있습니다. 큐를 사용하여 작업을 관리하므로, 작업의 순서를 유지하면서도 빠른 처리가 가능합니다.

사용 편의성

  • p-limit:

    'p-limit'는 사용하기 쉬운 API를 제공하여, 비동기 작업의 동시 실행 수를 쉽게 설정하고 관리할 수 있습니다. Promise 기반의 작업을 간단하게 제한할 수 있어, 코드의 가독성을 높여줍니다.

  • fastq:

    'fastq'는 간단한 API를 제공하여 비동기 작업을 쉽게 추가하고 관리할 수 있습니다. 작업을 큐에 추가하고, 완료된 작업에 대한 콜백을 설정하는 것이 직관적입니다.

에러 처리

  • p-limit:

    'p-limit'는 Promise를 반환하는 작업에 대해 에러 처리를 쉽게 할 수 있도록 설계되어 있습니다. 각 작업의 성공 및 실패를 관리하여, 전체 프로세스의 안정성을 높입니다.

  • fastq:

    'fastq'는 각 비동기 작업의 에러를 개별적으로 처리할 수 있는 기능을 제공합니다. 이를 통해 특정 작업에서 발생한 에러가 전체 작업 흐름에 영향을 미치지 않도록 할 수 있습니다.

비동기 흐름 제어

  • p-limit:

    'p-limit'는 비동기 작업의 실행 순서를 제어하는 데 유용합니다. 특정 수의 작업이 완료될 때까지 대기하고, 이후 작업을 실행하여 리소스를 효율적으로 사용할 수 있습니다.

  • fastq:

    'fastq'는 비동기 작업의 흐름을 제어하여, 특정 작업이 완료된 후 다음 작업을 실행하도록 설정할 수 있습니다. 이는 복잡한 비동기 로직을 간단하게 관리할 수 있게 합니다.

선택 방법: p-limit vs fastq

  • p-limit:

    동시에 실행할 수 있는 비동기 작업의 수를 제한하고 싶다면 'p-limit'를 선택하세요. 이는 시스템 리소스를 절약하고 과부하를 방지하는 데 도움이 됩니다.

  • fastq:

    비동기 작업을 큐에 추가하고 병렬로 실행해야 하는 경우 'fastq'를 선택하세요. 특히 여러 개의 비동기 작업을 동시에 처리해야 할 때 유용합니다.

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…