import type { Signal, ValueReactor } from "../reactor-core/index.ts" import { signal } from "../reactor-core/index.ts" import { subscribe } from "./utility.ts" export interface FromPromiseSyncOptions { target: Promise } /** * @description Converts a Promise into a Signal that updates its value * when the Promise resolves. * * @see {@link fromPromiseAsync} for an async version. */ export const fromPromiseSync = (options: FromPromiseSyncOptions): Signal => { const { target } = options const result = signal(() => undefined) void target.then((value) => { return result.set(value) }) return result } export interface FromPromiseAsyncOptions { target: Promise } /** * @description Converts a Promise into a Signal that is initialized * with the resolved value of the Promise. * * @see {@link fromPromiseSync} for a sync version. */ export const fromPromiseAsync = async ( options: FromPromiseAsyncOptions, ): Promise> => { const { target } = options const value = await target const result = signal(() => value) return result } export interface ToPromiseOptions { target: ValueReactor } /** * @description Converts a ValueReactor into a Promise that resolves * with the next value emitted by the ValueReactor. */ export const toPromise = async (options: ToPromiseOptions): Promise => { const { target } = options let _resolve: (value: V) => void const promise = new Promise((resolve) => { _resolve = resolve }) const unsubscribe = subscribe({ target, subscriber: (value) => { unsubscribe() _resolve(value) }, }) return await promise }