在节点中使用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循环吗?我已经搜索过了,但是没有找到关于异步迭代器的文档。
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?
);发布于 2021-10-09 09:33:32
我的建议是如何使用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类似于在将数组中的所有项添加到documents之前使用Promise.all对它们执行await操作。
我不相信在vanilla fp-ts中有更好的方法。有评论指出,其他库可能对迭代器有更好的支持,但我想介绍Task,它是用于异步工作的fp-ts monad。一旦定义了整个Task,就像调用函数一样调用它,它会将值转换为Promise。
const docs = await documents();https://stackoverflow.com/questions/68741811
复制相似问题