toPromiseValue
类似 Vue 内置的 toValue,但支持异步来源:把「取原始值 → 判断是否为 Promise → await」封装成一步,始终返回 Promise<T>。toValue 只能同步规范化值 / Ref / getter,遇到异步来源时需要自己写 await 和类型判断;配合 VueUse 的 computedAsync 即可优雅地驱动异步数据(如从服务端拉取的数据)。
Usage
ts
import { computedAsync, ref } from '@vueuse/core';
import { toPromiseValue } from 'vesium';
// Promise 实例、异步函数、普通 Ref 都能直接传入
const data = computedAsync(() => toPromiseValue(ref(Promise.resolve('Hello World'))));
// data.value -> 'Hello World'
// 需要结果时直接 await(返回值始终是 Promise)
const value = await toPromiseValue('Hello World');
// value -> 'Hello World'配置项
raw- 解析完成后是否用toRaw解包为原始值(如reactive代理对象),默认true。
返回值
Promise<T>- 解析后的值;即使数据源是同步的,返回值也始终是Promise。
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>;