💻 Dev

🛠️ 처음부터 만드는 Promise Queue — p-queue 스타일 비동기 작업 대기열 22줄 구현

Promise Queue란?


여러 비동기 작업을 대기열에 담아 동시 실행 수를 제한하는 패턴입니다.
  • 💪 동시성 제어: 최대 N개 작업만 동시 실행 (메모리/API 제한 회피)

  • 📝 FIFO 순서: 추가 순서대로 처리

  • 자동 스케줄: 작업 완료 시 다음 작업 자동 시작

  • 코드로 배우기


    ```typescript
    class PQueue {
    private queue = [];
    private running = 0;
    private concurrency;
    constructor(opts = {}) {
    this.concurrency = opts.concurrency ?? 1;
    }
    async add(fn) {
    return new Promise((resolve, reject) => {
    this.queue.push({ fn, resolve, reject });
    this.process();
    });
    }
    private async process() {
    while (this.running < this.concurrency && this.queue.length) {
    this.running++;
    const { fn, resolve, reject } = this.queue.shift();
    fn().then(resolve, reject).finally(() => {
    this.running--;
    this.process();
    });
    }
    }
    }
    ```

    실전 예제


    ```typescript
    const q = new PQueue({ concurrency: 3 });
    // 동시 최대 3개 API 요청
    const urls = ['url1', 'url2', ..., 'url100'];
    const results = await Promise.all(
    urls.map(url => q.add(() => fetch(url)))
    );
    ```

    심화: 우선순위 큐


    Task 객체에 `priority` 필드를 추가하고 `queue.sort()`로 정렬하면 우선순위 지원 가능합니다.

    실제 사용


  • p-queue (npm): 가장 인기 있는 구현, 타임아웃·이벤트 지원

  • bull: Redis 기반 Job Queue, 대규모 시스템용

  • Node.js Stream Backpressure: 내장 backpressure 메커니즘

  • 핵심: 비동기 작업을 제어 가능한 흐름으로 만드는 것이 목표입니다.
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!