safe-clone-async
v1.0.3
Published
A clean alternative to try/catch for async code, returning a tuple [data, error].
Maintainers
Readme
safe-clone-async
A clean, safe alternative to try/catch for async code.
Inspired by safe-await, safe-clone wraps your promises and returns a tuple [data, error], ensuring your code never throws unhandled errors.
Features
- ✅ Never throws: Errors are caught and returned as values.
- ✅ Type-safe: Generic support for return types and error types.
- ✅ Works with any Promise: Compatible with all async functions and libraries.
- ✅ Dual Support: Works with both ES Modules (ESM) and CommonJS (CJS).
- ✅ Zero Dependencies: Lightweight and fast.
Installation
npm install safe-clone-asyncUsage
Basic Usage
Use safeClone to wrap any promise. It returns an array where the first element is the data (or null) and the second is the error (or null).
import { safeClone } from 'safe-clone-async';
async function getUser() {
const [user, error] = await safeClone(fetchUser(1));
if (error) {
console.error('Failed to fetch user:', error);
return;
}
console.log('User data:', user);
}With Custom Error Types
You can specify the error type for better type safety.
import { safeClone } from 'safe-clone-async';
interface ApiError {
message: string;
code: number;
}
// ... inside async function
const [data, error] = await safeClone<User, ApiError>(fetchUser(1));
if (error) {
// error is typed as ApiError
console.log(error.code);
}CommonJS (require)
const { safeClone } = require('safe-clone-async');
safeClone(somePromise).then(([data, error]) => {
// ...
});API
safeClone<T, E = Error>(promise: Promise<T>): Promise<[T | null, E | null]>
- promise: The promise to execute.
- Returns: A promise that resolves to:
[data, null]if the promise resolves.[null, error]if the promise rejects.
License
MIT
Author: Ahmer Arain
