Effect.gen
code:ts
const main = fetchRequest.pipe(
Effect.filterOrFail(
(response) => response.ok,
(): FetchError => new FetchError(),
),
Effect.flatMap(jsonResponse),
Effect.catchTags({
FetchError: () => Effect.succeed("Fetch error"),
JsonError: () => Effect.succeed("Json error"),
}),
);
これを Effect.gen を用いると、従来の TypeScript の構文のように記述することが可能となる
code:ts
const main = Effect.gen(function* () {
const response = yield* fetchRequest;
if (!response.ok) return yield* new FetchError();
return yield* jsonResponse(response);
});
このコードは async / await のコードを、以下のように変換したものと近しい
async を Effect.gen に置き換える
無名関数をジェネレータ関数に置き換える
await と throw を yield* に置き換える
code:ts
const main = async () => {
const response = await fetchRequest();
if (!response.ok) throw new FetchError()
return await jsonResponse(response);
};