2

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

const documents: Record<string, any>[] = [];
let cursor = db.collection('randomcollection').find();

for await (let doc of cursor) {
  documents.push(document);
}

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

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

1 回答 1

0

我对如何编写此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.

我不相信 vanilla 有更好的方法fp-ts。有评论指出其他库可能对迭代器有更好的支持,但我想介绍一下Task哪个是fp-ts异步工作的 monad。一旦你定义了一个整体Task,你就可以像函数一样调用它,并将值转换为Promise.

const docs = await documents();
于 2021-10-09T09:33:31.793 回答