Created
March 25, 2023 00:17
-
-
Save cowboyd/dcf716aeaf04a69cf96a0fda86a606f0 to your computer and use it in GitHub Desktop.
go in terms of spawn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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