Skip to content

Instantly share code, notes, and snippets.

@dmmulroy
Created May 30, 2025 11:45
Show Gist options
  • Save dmmulroy/81cf34e4585a9c328d487e9838d7ae28 to your computer and use it in GitHub Desktop.
Save dmmulroy/81cf34e4585a9c328d487e9838d7ae28 to your computer and use it in GitHub Desktop.
/**
* Utility functions for creating `PromiseSettledResult` instances.
*
* Provides methods to construct fulfilled and rejected promise results,
* ensuring they resolve asynchronously.
*/
const PromiseSettledResult = {
/**
* Creates a fulfilled `PromiseSettledResult`.
*
* @param {A} value - The resolved value of the promise.
* @returns {Promise<PromiseSettledResult<A>>} A promise resolving to a fulfilled result.
*/
succeed: <A>(value: A): Promise<PromiseSettledResult<A>> => {
return Promise.resolve({ status: 'fulfilled', value });
},
/**
* Creates a rejected `PromiseSettledResult`.
*
* @param {unknown} reason - The reason for rejection.
* @returns {Promise<PromiseRejectedResult>} A promise resolving to a rejected result.
*/
fail: (reason: unknown): Promise<PromiseRejectedResult> => {
return Promise.resolve({ status: 'rejected', reason });
},
};
/**
* Converts an Effect into a `PromiseSettledResult`.
*
* Runs the provided Effect using the given runtime and converts the result
* into a settled promise result. If the effect succeeds, it returns a fulfilled
* result. If it fails, the error is squashed and returned as a rejected result.
*
* @param {ManagedRuntime.ManagedRuntime<R, E>} runtime - The Effect runtime to execute within.
* @returns A function that takes an effect and returns a settled promise result.
*/
export const makeRunSettledPromise =
<R, E>(runtime: ManagedRuntime.ManagedRuntime<R, E>) =>
async <Success, Error>(
effect: Effect.Effect<Success, Error>,
): Promise<PromiseSettledResult<Success>> => {
return runtime.runPromiseExit(effect).then((exit) => {
if (Exit.isSuccess(exit)) {
return PromiseSettledResult.succeed(exit.value);
}
return PromiseSettledResult.fail(Cause.squash(exit.cause));
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment