【问题标题】:fp-ts call async function inside mapLeftfp-ts 在 mapLeft 中调用异步函数
【发布时间】:2020-05-28 13:10:15
【问题描述】:

我是 fp-ts 的新手,所以请帮我解决我的问题: 我需要使用异步函数在不同级别上多次记录相同的错误。这是我的示例代码:

const myProgram = pipe(
    tryCatch(() => someAsyncFunc(), toError),
    mapLeft(async (err1) => {
        await loggerAsyncFunc();
        return err1;
    }),
)

const main = pipe(
    myProgram,
    mapLeft((err2) => {
        // err2 is a pending promise :(
    })
)();

我正在使用mapLeft 来执行此操作,但它不起作用。 我需要做什么才能在err2 中有错误的值 (err1) 而不是挂起的承诺?

【问题讨论】:

  • 你没有提供类型,所以我只能猜测tryCatch 返回一个Either。由于异步函数返回Promises,因此您可能有一个Either<Promise<A>, R>,也就是说,您需要将mapLeftmap 类型的map 实例组合在一起,FP-TS 希望提供这种类型。

标签: typescript asynchronous error-handling functional-programming fp-ts


【解决方案1】:

假设您正在使用TaskEither,orElse 可以将Task 链接在左侧。

const myProgram = pipe(
    TE.tryCatch(() => someAsyncFunc(), toError),
    // orElse is like a chain on the left side
    TE.orElse(err1 => pipe(
        TE.rightTask(longerAsyncFunc),
        TE.chain(() => TE.left(err1))
    )),
);

const main = pipe(
    myProgram,
    mapLeft((err2) => {
        // err2 is no longer a promise
    })
)();

【讨论】:

    猜你喜欢
    • 2020-04-18
    • 2021-10-29
    • 2019-01-20
    • 1970-01-01
    • 2020-03-09
    • 2021-12-25
    • 2020-04-02
    • 2012-07-25
    • 1970-01-01
    相关资源
    最近更新 更多