fp-ts在管道中间使用异步功能

时间:2019-12-30 06:15:22

标签: typescript asynchronous functional-programming pipe fp-ts

我有3个功能,f1f2f3

f1f3同步并返回Option<string>,但是f2是异步函数返回Promise<Option<string>>

如何在单个管道中使用这三个功能?

这是我的代码:

import {some, chain} from 'fp-ts/lib/Option';
import {pipe} from 'fp-ts/lib/pipeable';

const f1 = (input: string) => {
    return some(input + " f1")
};
const f2 = async (input: string) => {
    return some(input + " f2")
};
const f3 = (input: string) => {
    return some(input + " f3");
};

const result = pipe(
    "X",
    f1,
    chain(f2),
    chain(f3),
);

console.log("result", result);

1 个答案:

答案 0 :(得分:0)

我找到了使用TaskOption

的解决方案

这是我的代码:

import * as O from 'fp-ts/lib/Option';
import * as TO from 'fp-ts-contrib/lib/TaskOption';
import {pipe} from 'fp-ts/lib/pipeable';
import {flow} from 'fp-ts/lib/function';

const f1 = (input: string): O.Option<string> => {
    return O.some(input + " f1")
};
const f2 = (input: string): TO.TaskOption<string> => async () => {
    return O.some(input + " f2")
};
const f3 = (input: string): O.Option<string> => {
    return O.some(input + " f3");
};

pipe(
    "X",
    flow(f1, TO.fromOption),
    TO.chain(f2),
    TO.chain(flow(f3,TO.fromOption)),
)().then(console.log);

我们使用Option将所有TaskOption转换为TO.fromOption