orElse()
orElse<
T>(fn,fallback):T
Executes a function and returns its result, or a fallback value if an error occurs.
Type Parametersโ
T: Tโ
The return type.
Parametersโ
fn: () => Tโ
The function to execute.
fallback: Tโ
The value to return if the function throws an error.
Returns: Tโ
The result of the function or the fallback value.
Sinceโ
2.0.0
Exampleโ
const result = orElse(() => JSON.parse('invalid json'), {});
console.log(result); // {}
const value = orElse(() => localStorage.getItem('key'), 'default');
console.log(value); // 'default' if localStorage throws or key doesn't exist
const number = orElse(() => parseInt('abc'), 0);
console.log(number); // 0