filter()
Conditionally succeed or fail based on a predicate.
Syntax
typescript
task.filter(
predicate: (value: T) => boolean | Promise<boolean>,
errorMessage?: string
): FuturableTask<T>Parameters
predicate
Function that tests the value. If returns false, the task fails.
errorMessage (optional)
Custom error message when predicate fails. Default: "Filter predicate failed"
Return Value
A new FuturableTask<T> that fails if the predicate returns false.
Examples
Basic Validation
typescript
const task = FuturableTask
.of(() => fetch('/api/user'))
.map(res => res.json())
.filter(user => user.age >= 18);
try {
const adult = await task.run();
} catch (error) {
console.log('User is not an adult');
}Custom Error Message
typescript
const task = FuturableTask
.of(() => getUserInput())
.filter(
input => input.length >= 3,
'Input must be at least 3 characters'
);Async Predicate
typescript
const task = FuturableTask
.of(() => fetchDocument())
.filter(async doc => await validateDocument(doc));Multiple Filters
typescript
const task = FuturableTask
.of(() => fetchProduct())
.filter(p => p.price > 0, 'Price must be positive')
.filter(p => p.stock > 0, 'Product out of stock')
.filter(p => !p.discontinued, 'Product discontinued');