Skip to content

toPromiseValue

Similar to Vue's built-in toValue, but supports asynchronous sources: it wraps "unwrapping the source → checking whether it is a Promiseawaiting it" into a single step and always returns a Promise<T>. toValue can only normalize values, Refs, and getters synchronously, so async sources require manual await and type checks; this pairs naturally with VueUse's computedAsync for driving async data (e.g. fetched from a server).

Usage

ts
import { computedAsync, ref } from '@vueuse/core';
import { toPromiseValue } from 'vesium';

// Promise instances, async functions, and plain Refs can all be passed in
const data = computedAsync(() => toPromiseValue(ref(Promise.resolve('Hello World'))));
// data.value -> 'Hello World'

// Await directly when you need the result (the return value is always a Promise)
const value = await toPromiseValue('Hello World');
// value -> 'Hello World'

Options

  • raw - Whether to unwrap the resolved value with toRaw after resolution (e.g. reactive proxy objects), default true.

Return Value

  • Promise<T> - the resolved value; always a Promise, even when the source is synchronous.

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>;