0 day streak
javascript / intermediate
Snippet

Safe Async Operations Using Result Tuples in Vue Methods

Returning [data, error] tuples from async functions avoids unhandled promise rejections and keeps Vue component control flow explicit without deeply nested try-catch blocks.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { ref } from 'vue';
export function useSafeAsync(asyncFn) {
const isExecuting = ref(false);
async function run(...args) {
isExecuting.value = true;
try {
const result = await asyncFn(...args);
return [result, null];
} catch (error) {
const normalized = error instanceof Error ? error : new Error(String(error));
return [null, normalized];
} finally {
isExecuting.value = false;
}
}
return { run, isExecuting };
}
vue
Breakdown
1
const result = await asyncFn(...args);
Awaits the original async function with forwarded arguments.
2
return [result, null];
Returns a success tuple containing the resolved value and a null error.
3
const normalized = error instanceof Error ? error : new Error(String(error));
Converts unknown thrown non-Error values into standardized Error instances.
4
return [null, normalized];
Returns an error tuple containing null data and the caught error object.