Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Created March 25, 2023 00:17
Show Gist options
  • Save cowboyd/dcf716aeaf04a69cf96a0fda86a606f0 to your computer and use it in GitHub Desktop.
Save cowboyd/dcf716aeaf04a69cf96a0fda86a606f0 to your computer and use it in GitHub Desktop.
go in terms of spawn
import type { Operation, Task, Result, Port } from "https://deno.land/x/effection/mod.ts";
import { action, spawn, createContext } from "https://deno.land/x/effection/mod.ts";
const ErrorContext = createContext<Port<Error, never>>("error");
export function* go<T>(op: () => Operation<T>): Operation<Task<Result<T>>> {
return yield* spawn(function*() {
try {
return Ok(yield* call(op));
} catch (error) {
let { send } = yield* ErrorContext;
yield* send(error);
return Err(error);
}
});
}
function call<T>(op: () => Operation<T>): Operation<T> {
return action(function*(resolve) {
resolve(yield* op());
})
}
function Ok<T>(value: T): Result<T> {
return { type: "resolved", value };
}
function Err<T>(error: Error): Result<T> {
return { type: "rejected", error };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment