跳至内容

toPromiseValue

toPromiseValue 类似于 Vue 内置的 toValue,后者将值、Refs 或 getters 规范化为普通值,而 toPromiseValue 则将其规范化为 Promise 实例。建议与 VueUse 的 computedAsync 搭配使用,以便更好地处理异步数据。

Usage

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

// 处理 Promise 实例
const promiseRef = ref(Promise.resolve('Hello World'));
const data = computedAsync(() => toPromiseValue(promiseRef));
// data.value -> 'Hello World'

// 处理异步函数
async function asyncFn() {
  return 'Hello World';
}
const data = computedAsync(() => toPromiseValue(asyncFn));
// data.value -> 'Hello World'

// 处理普通的 Ref
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>;