import { Result } from "./Result.js"; export class ResultAsync { constructor(private readonly promise: Promise>) {} // Wrap a function returning a Promise>. public static from(fn: () => Promise>): ResultAsync { return new ResultAsync(fn()); } // Wrap a successful value. public static ok(value: T): ResultAsync { return new ResultAsync(Promise.resolve(Result.ok(value))); } // Wrap a failure. public static fail(error: E): ResultAsync { return new ResultAsync(Promise.resolve(Result.fail(error))); } // Await the wrapped result. public async unwrap(): Promise> { return this.promise; } // Transform the success value. public mapAsync(fn: (value: TValue) => U | Promise): ResultAsync { const newPromise = this.promise.then(async res => { if (res.isOk()) { return Result.ok(await fn(res.value)); } return Result.fail(res.error); }); return new ResultAsync(newPromise); } // Transform the error value. public mapErrorAsync(fn: (error: TError) => F | Promise): ResultAsync { const newPromise = this.promise.then(async res => { if (res.isFail()) { return Result.fail(await fn(res.error)); } return Result.ok(res.value); }); return new ResultAsync(newPromise); } // Chain another async Result. public flatMapAsync(fn: (value: TValue) => ResultAsync): ResultAsync { const newPromise = this.promise.then(async res => { if (res.isFail()) { return Result.fail(res.error); } return await fn(res.value).unwrap(); }); return new ResultAsync(newPromise); } // Match success/failure (like sync Result). public async match(handlers: { ok: (value: TValue) => U; fail: (error: TError) => U; }): Promise { const result = await this.unwrap(); if (result.isOk()) { return handlers.ok(result.value); } return handlers.fail(result.error); } }