The fromSafePromise function converts a Promise<T> that you know will never reject into a ResultAsync<T, E>. Unlike fromPromise, it does not require an error handler because it assumes the promise will always resolve successfully.fromSafePromise is a top-level export that references ResultAsync.fromSafePromise.
Use with CautionOnly use this function when you are absolutely certain the promise will not reject. If the promise does reject, the ResultAsync will reject as well, breaking the Result abstraction. When in doubt, use fromPromise instead.
import { fromSafePromise } from 'neverthrow'// Convert a synchronous value to ResultAsync for API consistencyfunction toResultAsync<T>(value: T): ResultAsync<T, never> { return fromSafePromise(Promise.resolve(value))}// Usage: Mix sync and async operations seamlesslyfunction processData(useCache: boolean) { if (useCache) { // Return cached value as ResultAsync return toResultAsync(getCachedData()) } else { // Fetch fresh data return fetchData() }}
// Inside the Ok classasyncMap<U>(f: (t: T) => Promise<U>): ResultAsync<U, E> { // Uses fromSafePromise because f is expected to return a resolved promise return ResultAsync.fromSafePromise(f(this.value))}
import { fromPromise } from 'neverthrow'const result = fromPromise( new Promise(resolve => setTimeout(() => resolve(42), 1000)), () => 'This will never happen' // Required but unnecessary)
import { fromSafePromise } from 'neverthrow'const result = fromSafePromise( new Promise(resolve => setTimeout(() => resolve(42), 1000)))// No error handler needed
import { fromSafePromise } from 'neverthrow'// Error type defaults to 'never'const result1 = fromSafePromise(Promise.resolve(42))// result1 type: ResultAsync<number, never>// You can specify error type for API consistencyconst result2 = fromSafePromise<number, string>(Promise.resolve(42))// result2 type: ResultAsync<number, string>// (even though it will never have a string error)
// BAD: fetch can rejectconst result = fromSafePromise( fetch('https://api.example.com/data'))// If fetch fails, ResultAsync will reject (breaks abstraction)// GOOD: Use fromPromise insteadconst result = fromPromise( fetch('https://api.example.com/data'), () => 'FetchError')
Don’t Use with Untrusted Promises
// BAD: Third-party library might rejectconst result = fromSafePromise( untrustedLibrary.doSomething())// GOOD: Wrap in error handlingconst result = fromPromise( untrustedLibrary.doSomething(), (error) => handleError(error))