Skip to main content

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