🛠️ 처음부터 만드는 Promise Queue — 동시 실행 개수를 제한하기
API 100개를 동시에 호출하면? 서버가 거부하거나 브라우저가 멈춥니다. Promise Queue는 동시에 실행되는 비동기 작업 수를 제한하는 패턴입니다.
대기열(queue)에 작업을 넣고, 동시 실행 슬롯이 빌 때마다 다음 작업을 꺼내 실행합니다.
```typescript
function createQueue(concurrency: number) {
const queue: (() => Promise)[] = [];
let running = 0;
function next() {
while (running < concurrency && queue.length > 0) {
const task = queue.shift()!;
running++;
task().finally(() => {
running--;
next();
});
}
}
return function add(fn: () => Promise): Promise {
return new Promise((resolve, reject) => {
queue.push(() => fn().then(resolve, reject));
next();
});
};
}
```
```typescript
const enqueue = createQueue(3); // 최대 3개 동시 실행
const urls = Array.from({ length: 20 }, (_, i) => `https://api.example.com/item/${i}`);
const results = await Promise.all(
urls.map(url => enqueue(() => fetch(url).then(r => r.json())))
);
console.log(results); // 20개 결과, 3개씩 순차 실행됨
```
| 상황 | concurrency 값 |
|---|---|
| 외부 API rate limit | 2~5 |
| 파일 동시 읽기 | 10~50 |
| DB 커넥션 풀 | 풀 크기에 맞춤 |
1. `add()` 호출 → 작업을 queue에 추가하고 `next()` 실행
2. `next()` → 슬롯이 남아있으면 queue에서 꺼내 실행
3. 작업 완료 → `running--` 후 다시 `next()` 호출
4. 반환된 Promise는 실제 작업이 완료될 때 resolve
핵심은 `finally`입니다. 성공이든 실패든 슬롯을 반환해야 큐가 멈추지 않습니다.
> 💡 실전에서는 [p-limit](https://github.com/sindresorhus/p-limit) 라이브러리가 이 패턴을 구현합니다. 원리를 이해한 뒤 라이브러리를 쓰면 디버깅이 훨씬 쉬워집니다.
핵심 아이디어
대기열(queue)에 작업을 넣고, 동시 실행 슬롯이 빌 때마다 다음 작업을 꺼내 실행합니다.
구현
```typescript
function createQueue(concurrency: number) {
const queue: (() => Promise
let running = 0;
function next() {
while (running < concurrency && queue.length > 0) {
const task = queue.shift()!;
running++;
task().finally(() => {
running--;
next();
});
}
}
return function add
return new Promise
queue.push(() => fn().then(resolve, reject));
next();
});
};
}
```
사용 예시
```typescript
const enqueue = createQueue(3); // 최대 3개 동시 실행
const urls = Array.from({ length: 20 }, (_, i) => `https://api.example.com/item/${i}`);
const results = await Promise.all(
urls.map(url => enqueue(() => fetch(url).then(r => r.json())))
);
console.log(results); // 20개 결과, 3개씩 순차 실행됨
```
왜 유용한가?
| 상황 | concurrency 값 |
|---|---|
| 외부 API rate limit | 2~5 |
| 파일 동시 읽기 | 10~50 |
| DB 커넥션 풀 | 풀 크기에 맞춤 |
동작 원리
1. `add()` 호출 → 작업을 queue에 추가하고 `next()` 실행
2. `next()` → 슬롯이 남아있으면 queue에서 꺼내 실행
3. 작업 완료 → `running--` 후 다시 `next()` 호출
4. 반환된 Promise는 실제 작업이 완료될 때 resolve
핵심은 `finally`입니다. 성공이든 실패든 슬롯을 반환해야 큐가 멈추지 않습니다.
> 💡 실전에서는 [p-limit](https://github.com/sindresorhus/p-limit) 라이브러리가 이 패턴을 구현합니다. 원리를 이해한 뒤 라이브러리를 쓰면 디버깅이 훨씬 쉬워집니다.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!