diff --git a/core/result.ts b/core/result.ts index 2550c24..070c1db 100644 --- a/core/result.ts +++ b/core/result.ts @@ -834,11 +834,19 @@ export function errAsync( * You can optionally pass `errorFn` as the second argument to map rejected * error from `unknown` to `E`. */ -export function fromPromise( - promise: Promise, - errorFn?: ErrFn, -): AsyncResult { - return chain(promise.then(ok).catch((e) => err(errorFn ? errorFn(e) : e))); +export function fromPromise( + promise: Promise>, + errorFn?: ErrFn, +): AsyncResult { + return chain( + promise.then((v) => { + if (v instanceof Ok || v instanceof Err) { + return v; + } + + return ok(v); + }).catch((e) => err(errorFn ? errorFn(e) : e)), + ); } /** @@ -848,8 +856,16 @@ export function fromPromise( * **Ensure you know what you're doing, otherwise a thrown exception within this * promise will cause `AsyncResult` to reject.** */ -export function fromSafePromise(promise: Promise): AsyncResult { - return chain(promise.then(ok)); +export function fromSafePromise( + promise: Promise>, +): AsyncResult { + return chain(promise.then((v) => { + if (v instanceof Ok || v instanceof Err) { + return v; + } + + return ok(v); + })); } /** diff --git a/core/result_test.ts b/core/result_test.ts index b4ea2c1..31b9e5a 100644 --- a/core/result_test.ts +++ b/core/result_test.ts @@ -85,6 +85,18 @@ Deno.test("errAsync", async () => { Deno.test("fromPromise", async () => { assertEquals(await fromPromise(Promise.resolve(1)).unwrap(), 1); + assertEquals( + await fromPromise(Promise.resolve(ok(4))).unwrap(), + 4, + ); + assertEquals( + await fromPromise(Promise.resolve(err("qwe"))).unwrapErr(), + "qwe", + ); + assertEquals( + await fromPromise(Promise.resolve(okAsync(5))).unwrap(), + 5, + ); assertEquals( await fromPromise(Promise.reject("rejected error")).unwrapErr(), @@ -102,6 +114,18 @@ Deno.test("fromPromise", async () => { Deno.test("fromSafePromise", async () => { assertEquals(await fromSafePromise(Promise.resolve(1)).unwrap(), 1); + assertEquals( + await fromSafePromise(Promise.resolve(ok(4))).unwrap(), + 4, + ); + assertEquals( + await fromSafePromise(Promise.resolve(err("qwe"))).unwrapErr(), + "qwe", + ); + assertEquals( + await fromSafePromise(Promise.resolve(okAsync(5))).unwrap(), + 5, + ); await assertRejects( async () =>