Async Operations

Handling promises and concurrent requests.

The catchError function is designed to handle asynchronous tasks by wrapping Promises and returning a standardized Result object.

You can wrap any Promise, such as network requests or database queries.

async-fetch.ts
import { catchError } from '@catcherjs/core';

async function fetchUser(id: number) {
const [error, data] = await catchError(
fetch(`https://api.example.com/users/${id}`).then(res => res.json())
);

  if (error) {
      return null;
  }

  return data;

}

The library also provides catchErrorWithTimeout to handle operations that might hang.

timeout-usage.ts
import { catchErrorWithTimeout } from '@catcherjs/core';

const [error, data] = await catchErrorWithTimeout(
fetch('https://api.slow-service.com/data'),
5000
);

if (error) {
console.error('Operation failed or timed out:', error.message);
}

When dealing with multiple promises simultaneously, you can wrap Promise.all or Promise.allSettled.

If any promise in the array fails, the entire Promise.all fails. catchError will catch that single failure.

promise-all.ts
import { catchError } from '@catcherjs/core';

const [error, data] = await catchError(Promise.all([
fetch('https://api.example.com/posts/1').then(res => res.json()),
fetch('https://api.example.com/posts/2').then(res => res.json())
]));

if (error) {
throw new Error('One or more requests failed');
}

console.log(data.length);

Promise.allSettled never rejects. It resolves with an array of statuses.

promise-all-settled.ts
import { catchError } from '@catcherjs/core';

const [error, settledData] = await catchError(Promise.allSettled([
fetch('https://api.example.com/posts/1').then(res => res.json()),
fetch('https://invalid-url.example').then(res => res.json())
]));

if (!error) {
const successes = settledData.filter(r => r.status === 'fulfilled');
const failures = settledData.filter(r => r.status === 'rejected');

  console.log(successes.length);
  console.log(failures.length);

}

Wrapping Promises adds negligible overhead. It is safe to use in high-throughput environments.

Component props

Prop
Type
Default

Component props

Prop
Type
Default