typescript / intermediate
Snippet
Safely Handling Async Promise Failures with Tupled Fallbacks
Wrapping Promises in a helper that returns a discriminated tuple ([error, null] or [null, data]) enables clean, Go-style error handling without requiring nested try-catch blocks everywhere.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type AsyncResult<T, E = Error> = Promise<[E, null] | [null, T]>;async function safeResult<T, E = Error>(promise: Promise<T>): AsyncResult<T, E> {try {const data = await promise;return [null, data];} catch (error) {return [error as E, null];}}async function demo() {const task = Promise.reject(new Error('Network loss'));const [err, result] = await safeResult(task);if (err) {console.error('Caught safely:', err.message);return;}console.log('Success:', result);}
Breakdown
1
type AsyncResult<T, E = Error> = Promise<[E, null] | [null, T]>;
Defines a strict generic union tuple type representing either failure or success outcomes.
2
return [error as E, null];
Catches any thrown exception and returns it cleanly as the first tuple element.
3
const [err, result] = await safeResult(task);
Destructures the tuple cleanly to allow immediate, type-safe conditional error checking.