Safe Execute is a versatile utility library that simplifies the execution of asynchronous tasks while handling errors gracefully. It not only provides core functions like tryCatch and safeExecute, but also includes three additional utilities—throttle, debounce, and cache—to improve performance and control.
You can add Safe Execute to your project using npm or pnpm:
-
Using
npm
:npm install @rahulc0dy/safe-execute
-
Using
pnpm
:pnpm add @rahulc0dy/safe-execute
-
tryCatch
Execute a promise safely and get either the data or error without try/catch blocks. -
safeExecute
Run synchronous or asynchronous functions with built-in error handling and optional callbacks.
-
throttle
Rate-limit a function so it executes at most once per defined interval. -
debounce
Delay function execution until a period of inactivity, ideal for inputs and filtering. -
cache
Cache the result of asynchronous calls to prevent redundant execution.
For detailed usage examples and API descriptions, refer to the sections below or check the documentation within your IDE.
Signature:
async function tryCatch<T, E = Error>(
promise: Promise<T>
): Promise<{ data: T | null; error: E | null }>;
- On success:
{ data: T, error: null }
- On failure:
{ data: null, error: E }
Signature:
async function safeExecute<T>(
fn: () => Promise<T> | T,
options?: {
onSuccess?: (result: T) => void;
onError?: (error: unknown) => void;
timeoutMs?: number;
}
): Promise<{
data: T | null;
isError: boolean;
isSuccess: boolean;
isLoading: boolean;
error: unknown;
}>;
Executes a given function safely, handling both synchronous and asynchronous operations, with optional callbacks and a timeout.
Signature:
function throttle<T extends (...args: any[]) => any>(fn: T, wait: number): T;
Returns a throttled version of the function that only executes once within the specified wait time.
Signature:
function debounce<T extends (...args: any[]) => any>(fn: T, delay: number): T;
Returns a debounced version of the function that delays execution until after the delay period has passed without further invocation.
Signature:
function cache<T extends (...args: any[]) => Promise<any>>(fn: T): T;
Caches the result of asynchronous function calls to avoid redundant executions when called with the same arguments.
Contributions are welcome! Please refer to our contributing guidelines for details on how to help improve the project.
This project is licensed under the MIT License.
If you encounter any issues or have questions, please open an issue for assistance.