Skip to content

Instantly share code, notes, and snippets.

@jeongtae
Last active May 30, 2023 04:50
Show Gist options
  • Save jeongtae/22e84b1d98975dfc4e83dcae53e0ff9c to your computer and use it in GitHub Desktop.
Save jeongtae/22e84b1d98975dfc4e83dcae53e0ff9c to your computer and use it in GitHub Desktop.
[Vue composable] This composable helps to track a pending state of async functions
import { computed, ref } from 'vue';
/**
* Tracks a pending state of async functions.
* 등록된 비동기 잡 함수의 진행 상태를 추적합니다.
*/
export function useAsyncJobsState() {
const pendingJobsCount = ref(0);
const isPending = computed(() => pendingJobsCount.value > 0);
function wrapAsyncJobFunction<F extends (...args: any[]) => Promise<any>>(
func: F,
): (...args: Parameters<F>) => ReturnType<F> {
const wrappedFunction = function (this: any, ...args: Parameters<F>): ReturnType<F> {
const promise = func.apply(this, args);
pendingJobsCount.value += 1;
return promise.finally(() => {
pendingJobsCount.value -= 1;
}) as ReturnType<F>;
};
return wrappedFunction;
}
return {
/**
* Will be true if some jobs are in progress.
* 진행 중인 비동기 잡 함수의 존재 여부입니다. 어느 한 잡이라도 진행 중이라면 `true`입니다.
*/
isPending,
/**
* Wrap async function to track its pending state.
* 상태 추적이 가능하도록 비동기 잡 함수를 래핑합니다.
*/
wrapAsyncJobFunction,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment