| [a762898] | 1 | /**
|
|---|
| 2 | * Attempt to execute an async function and return the result or error.
|
|---|
| 3 | * Returns a Promise that resolves to 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 async function.
|
|---|
| 8 | * @template {unknown} E - The type of the error that can be thrown by the async function.
|
|---|
| 9 | * @param {() => Promise<T>} func - The async function to execute.
|
|---|
| 10 | * @returns {Promise<[null, T] | [E, null]>} A Promise that resolves to a tuple containing either [null, result] or [error, null].
|
|---|
| 11 | *
|
|---|
| 12 | * @example
|
|---|
| 13 | * // Successful execution
|
|---|
| 14 | * const [error, data] = await attemptAsync(async () => {
|
|---|
| 15 | * const response = await fetch('https://api.example.com/data');
|
|---|
| 16 | * return response.json();
|
|---|
| 17 | * });
|
|---|
| 18 | * // If successful: [null, { ... data ... }]
|
|---|
| 19 | *
|
|---|
| 20 | * // Failed execution
|
|---|
| 21 | * const [error, data] = await attemptAsync(async () => {
|
|---|
| 22 | * throw new Error('Network error');
|
|---|
| 23 | * });
|
|---|
| 24 | * // [Error, null]
|
|---|
| 25 | *
|
|---|
| 26 | * // With type parameter
|
|---|
| 27 | * const [error, users] = await attemptAsync<User[]>(async () => {
|
|---|
| 28 | * const response = await fetch('https://api.example.com/users');
|
|---|
| 29 | * return response.json();
|
|---|
| 30 | * });
|
|---|
| 31 | * // users is typed as User[]
|
|---|
| 32 | */
|
|---|
| 33 | declare function attemptAsync<T, E>(func: () => Promise<T>): Promise<[null, T] | [E, null]>;
|
|---|
| 34 |
|
|---|
| 35 | export { attemptAsync };
|
|---|