| [a762898] | 1 | /**
|
|---|
| 2 | * Attempt to execute a function and return the result or error.
|
|---|
| 3 | * Returns a tuple where:
|
|---|
| 4 | * - On success: [null, Result] - First element is null, second is the result
|
|---|
| 5 | * - On error: [Error, null] - First element is the caught error, second is null
|
|---|
| 6 | *
|
|---|
| 7 | * @template {unknown} T - The type of the result of the function.
|
|---|
| 8 | * @template {unknown} E - The type of the error that can be thrown by the function.
|
|---|
| 9 | * @param {() => T} func - The function to execute.
|
|---|
| 10 | * @returns {[null, T] | [E, null]} A tuple containing either [null, result] or [error, null].
|
|---|
| 11 | *
|
|---|
| 12 | * @example
|
|---|
| 13 | * // Successful execution
|
|---|
| 14 | * const [error, result] = attempt(() => 42);
|
|---|
| 15 | * // [null, 42]
|
|---|
| 16 | *
|
|---|
| 17 | * // Failed execution
|
|---|
| 18 | * const [error, result] = attempt(() => {
|
|---|
| 19 | * throw new Error('Something went wrong');
|
|---|
| 20 | * });
|
|---|
| 21 | * // [Error, null]
|
|---|
| 22 | *
|
|---|
| 23 | * // With type parameter
|
|---|
| 24 | * const [error, names] = attempt<string[]>(() => ['Alice', 'Bob']);
|
|---|
| 25 | * // [null, ['Alice', 'Bob']]
|
|---|
| 26 | *
|
|---|
| 27 | * @note
|
|---|
| 28 | * Important: This function is not suitable for async functions (functions that return a `Promise`).
|
|---|
| 29 | * When passing an async function, it will return `[null, Promise<Result>]`, but won't catch any
|
|---|
| 30 | * errors if the Promise is rejected later.
|
|---|
| 31 | *
|
|---|
| 32 | * For handling async functions, use the `attemptAsync` function instead:
|
|---|
| 33 | * ```
|
|---|
| 34 | * const [error, data] = await attemptAsync(async () => {
|
|---|
| 35 | * const response = await fetch('https://api.example.com/data');
|
|---|
| 36 | * return response.json();
|
|---|
| 37 | * });
|
|---|
| 38 | * ```
|
|---|
| 39 | */
|
|---|
| 40 | declare function attempt<T, E>(func: () => T): [null, T] | [E, null];
|
|---|
| 41 |
|
|---|
| 42 | export { attempt };
|
|---|