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
);