我正在使用fp-ts库,我无法理解如何实现以下场景:
{
totalItems: 100,
perPage: 25,
books:[{...}, ...],
....
}const nrOfPages = Math.ceil(totalItems / perPage);现在的斗争是,最后,我想收集所有的书在一个物体内。基本上,我想等待结果和平面图他们在一起。同样重要的是,请求应该是顺序的,并且使用fp库。
const allBooks [{...},{...},{...}, ...];发布于 2022-09-25 05:56:36
您可以从traverseSeqArray模块中使用Task将一个页码数组映射到任务中,以获取每个页面,并且每个任务都将按顺序执行。然后,您可以使用concatAll (来自Monoid)连接书籍数组。
declare const traverseSeqArray: <A, B>(f: (a: A) => Task<B>) => (as: readonly A[]) => Task<readonly B[]>
declare const concatAll: <A>(M: Monoid<A>) => (as: readonly A[]) => Aimport * as M from 'fp-ts/lib/Monoid';
import * as RA from 'fp-ts/lib/ReadonlyArray';
import * as T from 'fp-ts/lib/Task';
import {flow, pipe} from 'fp-ts/lib/function';
declare const getBooks: (
shelf: Shelf,
page: number
) => T.Task<{totalItems: number; perPage: number; books: readonly Book[]}>;
const getAllBooks = (shelf: Shelf): T.Task<readonly Book[]> =>
pipe(
// Fetch the first page (assuming pages are zero-indexed)
getBooks(shelf, 0),
T.chain(({totalItems, perPage, books: firstPageBooks}) => {
const nrOfPages = Math.ceil(totalItems / perPage);
// e.g. [1, 2, 3] for 100 books and 25 per page
const pagesToFetch = Array.from(
{length: nrOfPages - 1},
(_, i) => i + 1
);
return pipe(
pagesToFetch,
// With each page...
T.traverseSeqArray(page =>
// ...fetch the books at the page
pipe(
getBooks(shelf, page),
T.map(({books}) => books)
)
),
// Now we have a Task<Book[][]> that we want to turn into
// a Task<Book[]> including the books from the first page
T.map(
flow(
// Prepend the first pages’ books
RA.prepend(firstPageBooks),
// Concatenate the Book[][] into a Book[]
M.concatAll(RA.getMonoid())
)
)
);
})
);本例假设getBooks没有失败,但是可以通过将Task切换到TaskEither轻松地修改tihs。
https://stackoverflow.com/questions/73733553
复制相似问题