首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在fp-ts中使用TaskEither与fetch API

在fp-ts中使用TaskEither与fetch API
EN

Stack Overflow用户
提问于 2020-06-02 15:43:22
回答 1查看 1.1K关注 0票数 2

我想以某种方式包装fp中的Fetch API:

  1. 创建请求
  2. 检查状态
  3. 如果状态正常返回json

代码语言:javascript
复制
import * as TE from 'fp-ts/lib/TaskEither';
import * as E from 'fp-ts/lib/Either';
import { flow } from 'fp-ts/lib/function';
import { pipe } from 'fp-ts/lib/pipeable';

const safeGet = (url: string): TE.TaskEither<Error, Response> => TE.tryCatch(
  () => fetch(url),
  (reason) => new Error(String(reason))
);

const processResponce = flow(
  (x: Response): E.Either<Error, Response> => {
    return x.status === 200
      ? E.right(x)
      : E.left(Error(x.statusText))
  },
  TE.fromEither
);

export const httpGet = (url: string): TE.TaskEither<Error, Response> => pipe(
  safeGet(url),
  TE.chain(processResponce)
);

在这个例子中,在运行httpGet之后,我会得到一个响应,并且需要手动地使用.json()方法。那么,我如何避免这种行为,让json进入管道呢?

EN

回答 1

Stack Overflow用户

发布于 2020-07-14 21:18:47

把这个锁在你的流量里?

代码语言:javascript
复制
const safeJson = <T = unknown>(resp: Response): TE.TaskEither<Error, T> => TE.tryCatch(
  () => resp.json(),
  (reason) => new Error(String(reason))
);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62155842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档