[英]Mixing Either and TaskEither in a pipe in fp-ts
當沒有任何功能是異步的時,我有以下程序可以正常工作。
interface Product {
count: number
pricePerItem: number
}
interface Tax {
tax: number
}
interface Delivery {
delivery: number
}
interface PTD { //ProductTaxDelivery
p: Product
t: number
d: number
}
function getProduct(): Either<Error, Product> {
return E.right({ count: 10, pricePerItem: 5 })
}
function getTax(p: Product): Either<Error, number> {
return E.right(p.pricePerItem * p.count * 0.085)
}
function getDelivery(p: Product): Either<Error, number> {
return E.right(p.count * 0.05)
//or maybe return E.left(Error('some error in delivery happened'))
}
function run(): Either<Error, PTD> {
return pipe(
E.Do,
E.bind('p', getProduct),
E.bind('tax', ({p}) => getTax(p)),
E.bind('delivery', ({p}) => getDelivery(p)),
E.map(({ p, tax, delivery }) => ({ p, t: tax, d: delivery }))
)
}
function main() {
pipe(
run(),
E.fold(
(e) => {
console.log(`error: ${e}`)
},
(it) => {
console.log(`ok ${it.p.count} ${it.p.pricePerItem} ${it.t} ${it.d}`)
}
)
)
}
main()
我遇到的問題是,如果我的函數之一,例如getDelivery()
是異步的,那么我不知道如何解決它。
這是我嘗試過的:
function getDelivery(p: Product): TaskEither<Error, number> {
return TE.right(p.count * 0.05)
}
TE.bind('delivery', ({p}) => getDelivery(p)),
和許多其他變體,但都以編譯器錯誤告終。
命令式風格的等價物是這樣的:
const getDelivery = async (p: Product) => {
return await something()
}
const run = async (): PTD => {
const product = getProduct()
const tax = getTax(product)
const delivery = await getDelivery(product)
return {
p: product, t: tax, d: delivery
}
}
使用fp-ts
的正確功能方式是什么(我認為這涉及Either
和TaskEither
)?
更新:我還嘗試將 Either 替換為 TaskEither,E 替換為 TE,但是當我嘗試fold
main()
時,問題現在是編譯器錯誤。 這是替換的代碼:
function getProduct(): TaskEither<Error, Product> {
return TE.right({ count: 10, pricePerItem: 5 })
}
function getTax(p: Product): TaskEither<Error, number> {
return TE.right(p.pricePerItem * p.count * 0.085)
}
function getDelivery(p: Product): TaskEither<Error, number> {
return TE.right(p.count * 0.05)
}
function run(): TaskEither<Error, PTD> {
return pipe(
TE.Do,
TE.bind('p', getProduct),
TE.bind('tax', ({ p }) => getTax(p)),
TE.bind('delivery', ({ p }) => getDelivery(p)),
TE.map(({ p, tax, delivery }) => ({ p, t: tax, d: delivery }))
)
}
function main() {
pipe(
run(),
TE.fold(
(e) => {
console.log(`error: ${e}`)
},
(it) => {
console.log(`ok ${it.p.count} ${it.p.pricePerItem} ${it.t} ${it.d}`)
//doNonFunctional()
}
)
)
}
main()
與(e) => {
一致,編譯器錯誤說:
error TS2345: Argument of type '(e: Error) => void' is not assignable to parameter of type '(e: Error) => Task<unknown>'.
Type 'void' is not assignable to type 'Task<unknown>'.
更新 2 OK,所以我得到了要編譯的代碼,但程序運行時沒有輸出
const printError = (e: Error): T.Task<unknown> => {
console.log(`error: ${e}`)
return () => Promise.resolve()
}
const printPTD = (ptd: PTD): T.Task<unknown> => {
console.log(`ok ${ptd.p.count} ${ptd.p.pricePerItem} ${ptd.t} ${ptd.d}`)
return () => Promise.resolve()
}
function run(): TaskEither<Error, PTD> {
return pipe(
TE.Do,
TE.bind('p', getProduct),
TE.bind('tax', ({ p }) => getTax(p)),
TE.bind('delivery', ({ p }) => getDelivery(p)),
TE.map(({ p, tax, delivery }) => ({ p, t: tax, d: delivery }))
)
}
function main() {
pipe(
run(),
TE.fold(
(e) => printError(e),
(ptd) => printPTD(ptd)
)
)
}
main()
問題是當您在main
中使用pipe
創建Task
時,您實際上並沒有運行任何東西。
這是Task
的定義方式:
interface Task<A> {
(): Promise<A>
}
// same as type <A> = () => Promise<A>
因為Task
是一個 thunk,所以您需要調用它來實際執行代碼。
async function main(): Promise<void> {
await pipe(
// ...
// vv note the call here
)()
}
main()
但是,我會這樣做:
const main: T.Task<void> = pipe(/* ... */)
main()
同樣, run
不需要是函數; 它可以是const run = pipe(/* ... */)
。
此外,還有一個Console
模塊,它提供返回IO
(一種用於副作用操作的類型)的日志函數。
你的代碼可以寫成
import * as Console from 'fp-ts/Console'
import * as E from 'fp-ts/Either'
import * as T from 'fp-ts/Task'
import * as TE from 'fp-ts/TaskEither'
import {pipe} from 'fp-ts/function'
// <A>(a: A) => Task<void>
const taskLog = T.fromIOK(Console.log)
// You can still keep getProduct and getTask synchronous
function getProduct(): E.Either<Error, Product> { /* ... */ }
function getTax(p: Product): E.Either<Error, number> { /* ... */ }
function getDelivery(p: Product): TE.TaskEither<Error, number> { /* ... */ }
const run: TE.TaskEither<Error, PTD> = pipe(
TE.Do,
// See below for what TE.fromEither(K) does
TE.bind('p', TE.fromEitherK(getProduct)),
TE.bind('tax', ({p}) => TE.fromEither(getTax(p))),
TE.bind('delivery', ({p}) => getDelivery(p)),
TE.map(({p, tax, delivery}) => ({p, t: tax, d: delivery}))
)
const main: T.Task<void> = pipe(
run,
TE.fold(
e => taskLog(`error: ${e}`),
it => taskLog(`ok ${it.p.count} ${it.p.pricePerItem} ${it.t} ${it.d}`)
)
)
main().catch(console.error)
TE.fromEither
將Either
轉換為TaskEither
:
export declare const fromEither: NaturalTransformation22<'Either', 'TaskEither'>
// same as
export declare const fromEither: <E, A>(fa: Either<E, A>) => TaskEither<E, A>
TE.fromEitherK
與fromEither
相同,但對於函數:
export declare const fromEitherK: <E, A extends readonly unknown[], B>(f: (...a: A) => Either<E, B>) => (...a: A) => TaskEither<E, B>
您現在可能已經猜到T.fromIOK
(用於taskLog
)做了什么:
export declare const fromIOK: <A, B>(f: (...a: A) => IO<B>) => (...a: A) => Task<B>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.