toPromiseValue
toPromiseValue
is similar to Vue's built-in toValue, which normalizes values, Refs, or getters into plain values. In contrast, toPromiseValue
normalizes them into Promise instances. It is recommended to use it alongside VueUse's computedAsync for better handling of asynchronous data.
Usage
ts
import { computedAsync, ref } from '@vueuse/core';
import { toPromiseValue } from 'vesium';
// Handling Promise instances
const promiseRef = ref(Promise.resolve('Hello World'));
const data = computedAsync(() => toPromiseValue(promiseRef));
// data.value -> 'Hello World'
// Handling async functions
async function asyncFn() {
return 'Hello World';
}
const data = computedAsync(() => toPromiseValue(asyncFn));
// data.value -> 'Hello World'
// Handling regular Refs
const normalRef = ref('Hello World');
const data = computedAsync(() => toPromiseValue(normalRef));
// data.value -> 'Hello World'
Type Definitions
typescript
import type { MaybeRef } from 'vue';
export type OnAsyncGetterCancel = (onCancel: () => void) => void;
export type MaybeAsyncGetter<T> = () => (Promise<T> | T);
export type MaybeRefOrAsyncGetter<T> = MaybeRef<T> | MaybeAsyncGetter<T>;
export interface ToPromiseValueOptions {
/**
* Determines whether the source should be unwrapped to its raw value.
* @default true
*/
raw?: boolean;
}
/**
* Similar to Vue's built-in `toValue`, but capable of handling asynchronous functions, thus returning a `await value`.
*
* Used in conjunction with VueUse's `computedAsync`.
*
* @param source The source value, which can be a reactive reference or an asynchronous getter.
* @param options Conversion options
* @returns The converted value.
*
* @example
* ```ts
*
* const data = computedAsync(async ()=> {
* return await toPromiseValue(promiseRef)
* })
*
* ```
*/
export declare function toPromiseValue<T>(source: MaybeRefOrAsyncGetter<T>, options?: ToPromiseValueOptions): Promise<T>;