Skip to content

fix: add withTimeout utility#79

Merged
moizycodes merged 1 commit into
moizycodes:mainfrom
Rasagnika-GR:issue-55fix
May 14, 2026
Merged

fix: add withTimeout utility#79
moizycodes merged 1 commit into
moizycodes:mainfrom
Rasagnika-GR:issue-55fix

Conversation

@Rasagnika-GR
Copy link
Copy Markdown
Contributor

🎯 Overview

Implements a reusable withTimeout() utility that wraps a Promise and rejects it if it exceeds a specified timeout duration. This addresses the need for fail-safe mechanisms in async operations like API calls and database requests that may hang or never resolve.

Closes #55

🔧 Changes Made

New File: utils/withTimeout.js

  • Implemented withTimeout(promise, timeout) using Promise.race()
  • Timer is cleared via .finally() after the promise settles to prevent memory leaks
  • Exported as a named ES6 export

Edge Cases Handled

  • Non-Promise input → rejects with TypeError
  • timeout <= 0 → rejects immediately with RangeError
  • Promise resolves before timeout → resolves normally
  • Promise never resolves → rejects with timeout error

🧪 Testing

// Happy path
const data = await withTimeout(fetchData(), 2000);

// Edge cases
withTimeout('not-a-promise', 1000); // TypeError: First argument must be a Promise
withTimeout(fetchData(), 0);        // RangeError: Timeout must be greater than 0
withTimeout(fetchData(), -1);       // RangeError: Timeout must be greater than 0

@moizycodes moizycodes merged commit e6225aa into moizycodes:main May 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement a withTimeout() Utility for Async Operations

2 participants