typescriptparallel-processingfp-ts

How to serialize task executions with TypeScript when using fp-ts?


I have some code that turns values in an array into asynchronous calls:

const createDiscordChannels = flow(
    A.map((channel: CreateChannelDto) => ({
        ...channel,
        provider,
        externalServerId: providerId,
    })),
    //* 📘 We need to check all the channels before we do anything
    //* because otherwise we can end up in an inconsistent state
    A.map(agentDispatcher.isChannelValid), // 👈 returns TaskEither
    A.map(TE.flatMap(agentDispatcher.ensureChannelExists)), // 👈 creates race condition
    A.map(RTE.fromTaskEither),
    RTE.sequenceArray
);

My problem is that A.map(TE.flatMap(agentDispatcher.ensureChannelExists)) will create a bunch of TaskEithers that are executing in parallel creating a race condition.

Is there a way to create and immediately await a TaskEither to execute them in a sequence instead of in parallel?


Solution

  • The short answer is to use sequenceSeqArray which will run each of the tasks sequentially and collect up the results into a single ReaderTaskEither. You're currently using RTE.sequenceArray which is similar, but has the behavior you're describing where each of the promises is started in parallel.