【问题标题】:fp-ts Using async function in middle of pipefp-ts 在管道中间使用异步函数
【发布时间】:2020-04-18 22:39:18
【问题描述】:

我有 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);

【问题讨论】:

  • 您有两个嵌套效果(异步和可选),因此您需要组合两个 monad。由于 monad 不能机械地组成,因此您必须使用 monad 转换器。我确信 FP-TS 提供 OptionT.
  • 是的,FP-TS 中有OptionT,但我不明白我应该如何使用它。你能告诉我如何在上面的示例代码中使用OptionT 吗?谢谢。
  • 我不知道fp-ts library。非常有趣。
  • 请阅读它的文档并帮助我解决我的问题

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


【解决方案1】:

我找到了使用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);

我们使用TO.fromOption 将所有Options 转换为TaskOptions。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-29
    • 2021-08-01
    • 2022-07-24
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2020-07-22
    • 2020-04-02
    相关资源
    最近更新 更多