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?
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.