With mongodb in node we can use async iterators. Basic example:
const documents: Record<string, any>[] = [];
let cursor = db.collection('randomcollection').find();
for await (let doc of cursor) {
documents.push(document);
}
How does async iterators translate to functional programming, using fp-ts? Is it possible to express the for loop above in fp-ts? I have searched, but found no documentation regarding async iterators.
const whereIamRightNow = pipe(
TE.bindTo('db')(createMongoClientWithEncryption),
TE.bind('cursor', ({ db }) => TE.of(getQueryCursor(dateRange)(db.client))),
// how to async iterate over query cursor and call a processing function for each record?
);
My suggestion for how to write this with
fp-tschange a little bit depending on the exact desired flow, but if you want to collect up all the awaited values of a collection ofPromisesI think you could do something like:sequenceArrayis similar toawaiting all items in the array withPromise.allbefore adding them todocuments.I don't believe there's any better way in vanilla
fp-ts. A comment indicated additional libraries which likely have better support specifically for iterators, but I wanted to introduceTaskwhich is thefp-tsmonad for asynchronous work. Once you have defined an entireTaskyou call it like a function and it transforms the value into aPromise.