本文介绍了并行运行一组TaskEithers,但如果1个或多个任务失败,则继续运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须并行执行IO调用数组,如果成功,则合并调用的内​​容.如果其中一个失败,则其他人将照常进行处理,但会收到一条错误消息.

I have to make an array of IO calls in parallel, and merge the contents of the call if successful. If one fails the others get processed as per normal, but an error message.

我关于如何实现的思考过程:

My thought process on how this can be implemented:

Array<TE<E, A>> -> TE<E, Array<A>> -> TE<E, MergedA> -> [E, A]

我目前正在做什么:

我目前正在对一系列TE进行测序,但是链中的任何故障都会产生剩余.

I am currently sequencing an array of TE, but any failure in the chain will yield a left.

pipe(
sequenceT(TE.taskEither)(arrayofTE), //TE<E,A>[] -> TE<E,A[]>
TE.map(mergeFn), //TE<E, A[]> -> TE<E, MergedA> 
???
)

如何停止短路?

推荐答案

您可以将T.task而不是TE.taskEither传递给sequence/sequenceT(文档):

You can pass T.task instead of TE.taskEither to sequence/sequenceT (docs):

TaskEither: array.sequence(T.task)(taskEithers)-与 sequenceT

TaskEither: array.sequence(T.task)(taskEithers) - same for sequenceT

sequence :并行运行相同类型的任务

import { pipeable as P, taskEither as TE, task as T, array as A, either as E } from "fp-ts";

const arrayofTE: TE.TaskEither<string, number>[] = [
  TE.right(1),
  TE.right(2),
  TE.left("Oh shit")
];

const run = P.pipe(
  // change to T.task instead of TE.taskEither here
  A.array.sequence(T.task)(arrayofTE),
  mergeFn
);

run(); // run side effect
// returns Promise<{"errors":["Oh shit"],"results":[1,2]}>

// whatever merged result you want to have; this one collects all errors and all results
declare function mergeFn(te: T.Task<E.Either<string, number>[]>): T.Task<Results> 

type Results = { errors: string[]; results: number[] };

sequenceT :并行运行不同类型的任务

import { apply as AP /* and others above */ } from "fp-ts";

// Here, TaskEither result can be number | boolean (success case), string on error
const arrayofTE = [TE.right(1), TE.right(true), TE.left("Oh shit")] as const;

const run = P.pipe(
  AP.sequenceT(T.task)(...arrayofTE), // we use sequenceT here and pass T.task again
  mergeFn
);

declare function mergeFn(a: T.Task<E.Either<string, number | boolean>[]>): T.Task<Results>

以下是具有mergeFn实现的沙箱,可以玩:序列序列T .希望有帮助!

Here are sandboxes with mergeFn implementation to play around: sequence , sequenceT. Hope, it helps!

这篇关于并行运行一组TaskEithers,但如果1个或多个任务失败,则继续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 22:02