orElseAsync()
orElseAsync<
T>(fn,fallback):Promise<T>
Executes an async function and returns its result, or a fallback value if an error occurs.
Type Parameters
T: T
The return type.
Parameters
fn: () => Promise<T>
The async function to execute.
fallback: T
The value to return if the function throws an error.
Returns: Promise<T>
A Promise that resolves to the result of the function or the fallback value.
Since
2.0.0
Example
const result = await orElseAsync(async () => {
const response = await fetch('/api/data');
return await response.json();
}, {});
console.log(result); // {} if fetch fails
const data = await orElseAsync(async () => {
const user = await getUserFromDB(id);
return user.profile;
}, null);
console.log(data); // null if user not found or DB error