带有ftp -ts和mongo的异步迭代器



mongodb在节点,我们可以使用异步迭代器。基本的例子:

const documents: Record<string, any>[] = [];
let cursor = db.collection('randomcollection').find();
for await (let doc of cursor) {
documents.push(document);
}

如何使用fp-ts将异步迭代器转换为函数式编程?有可能在fp-ts中表达上面的for循环吗?我已经搜索过了,但是没有找到关于async迭代器的文档。

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?
);

关于如何使用fp-ts编写此内容的建议根据所需的确切流程略有变化,但如果您想收集Promises集合的所有等待值,我认为您可以这样做:

import { pipe } from 'fp-ts/lib/function';
// Task is the `fp-ts` way of tracking asynchronous work
import * as T from 'fp-ts/lib/Task';
const documents: T.Task<readonly any[]> = pipe(
// For simplicity let's assume the db's find method returns a Task[]
db.collection('randomcollection').find(),
T.sequenceArray
);

sequenceArray类似于await,先用Promise.all将数组中的所有项添加到documents中。

我不相信在香草fp-ts中有更好的方法。一条注释指出,其他库可能对迭代器有更好的支持,但我想介绍Task,它是用于异步工作的fp-ts单子。一旦你定义了一个完整的Task,你就像调用一个函数一样调用它,它会把值转换成一个Promise

const docs = await documents();