扫一扫分享
Effect,这是一个功能强大的 TypeScript 框架,它提供了成熟的功能效果系统和丰富的标准库。
Effect 的幕后动机是辅助开发者通过所谓的结构化并发,一种允许多个复杂操作同时运行的编程范式,构建鲁棒可扩展的 App。
TypeScript 5.0 或更高版本
文件strict中启用的标志tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strict": true,
}
}
随着应用程序的增长,Effect 也会随之扩展,从而保持代码的简洁性和可维护性。
没有使用Effect
async function getTodo(
id: number
): Promise<
| { ok: true; todo: any }
| { ok: false; error: "InvalidJson" | "RequestFailed" }
> {
try {
const response = await fetch(`/todos/${id}`)
if (!response.ok) throw new Error("Not OK!")
try {
const todo = await response.json()
return { ok: true, todo }
} catch (jsonError) {
return { ok: false, error: "InvalidJson" }
}
} catch (error) {
return { ok: false, error: "RequestFailed" }
}
}
使用Effect
const getTodo = (
id: number
): Effect.Effect<unknown, HttpClientError> =>
Http.request.get(`/todos/${id}`).pipe(
Http.client.fetchOk(),
Http.response.json,
)
手机预览