orElseLazy()
orElseLazy<
T>(fn,fallbackFn):T
Executes a function and returns its result, or executes a fallback function if an error occurs. The fallback function is only executed when needed (lazy evaluation).
Type Parameters
T: T
The return type.
Parameters
fn: () => T
The function to execute.
fallbackFn: () => T
The function to execute if the first function throws an error.
Returns: T
The result of the function or the result of the fallback function.
Since
2.0.0
Example
const result = orElseLazy(
() => JSON.parse('invalid json'),
() => ({ error: 'Invalid JSON', timestamp: Date.now() })
);
console.log(result); // { error: 'Invalid JSON', timestamp: 1234567890 }
const config = orElseLazy(
() => localStorage.getItem('config'),
() => getDefaultConfig() // Only called if localStorage fails
);