🛠️ 처음부터 만드는 Promise Queue — p-queue 스타일 비동기 작업 대기열 22줄 구현
Promise Queue란?
여러 비동기 작업을 대기열에 담아 동시 실행 수를 제한하는 패턴입니다.
코드로 배우기
```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()`로 정렬하면 우선순위 지원 가능합니다.
실제 사용
핵심: 비동기 작업을 제어 가능한 흐름으로 만드는 것이 목표입니다.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!