🛠️ 처음부터 만드는 Promise Timeout — API 호출에 타임아웃 추가하는 12줄 구현
기본 구현 (12줄)
```typescript
function withTimeout
promise: Promise
ms: number
): Promise
return Promise.race([
promise,
new Promise
setTimeout(() => reject(new Error(`Timeout after ${ms}ms`)), ms)
)
]);
}
```
사용
```typescript
// 5초 타임아웃으로 API 요청
const data = await withTimeout(
fetch('/api/data').then(r => r.json()),
5000
);
// 실패 시 처리
try {
await withTimeout(slowAPI(), 3000);
} catch (e) {
if (e.message.includes('Timeout')) {
console.log('요청이 너무 오래 걸렸습니다');
}
}
```
Promise.race의 비결
`Promise.race()`는 먼저 완료되는 Promise를 반환한다. 타임아웃 Promise가 이기면 reject된다.
더 실전적으로는 AbortController 사용:
```typescript
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
fetch('/api/data', { signal: controller.signal });
```
Comments (0)
💬
No comments yet.
Be the first to comment!