Skip to content

Instantly share code, notes, and snippets.

@dmmulroy
Last active May 11, 2025 01:50
Show Gist options
  • Save dmmulroy/ab4f61d8dae3c94558018da56483417f to your computer and use it in GitHub Desktop.
Save dmmulroy/ab4f61d8dae3c94558018da56483417f 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));
});
};
// Pretend this is your main Layer with all your layers/deps/requirements
const dependencies = Layer.empty;
const runtime = ManagedRuntime.make(dependencies);
const runSettledPromise = makeRunSettledPromise(runtime);
declare const effect: Effect.Effect<number, string>;
async function main() {
const result: PromiseSettledResult<number> = await runSettledPromise(effect);
if (result.status === 'fulfilled') {
console.log('number: ', result.value);
return;
}
console.error('error message string: ', result.reason);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment