我正在尝试编写一个自定义asyncIterable来批量获取一些数据并循环遍历批处理。我试图这样做,以避免我的工人超时。以下是我的代码:
import { SomeDataInterfaceNotGeneric } from 'InterfaceDefinitionFile'
async getIterable(): Promise<
AsyncIterable<SomeDataInterfaceNotGeneric[]> // previously written as T
> {
const count = await getTotalCount()
const batchesCount = Math.ceil(count / BATCH_SIZE)
let i = 0
const iterator = {
async next(): Promise<IteratorResult<SomeDataInterfaceNotGeneric[]>> {
const data: SomeDataInterfaceNotGeneric[] = await repository.findByCriteria<
SomeDataInterfaceNotGeneric
>(searchCriteria, {
limit: BATCH_SIZE,
skip: i * BATCH_SIZE
}) // this function needs generic and the error points to this line
await Promise.all(
data.map(datum=> {
// augment some data to each item
return this.asyncTask(datum)
})
)
i++
return {
value: data,
done: i === batchesCount
}
}
}
return {
[Symbol.asyncIterator]() {
return iterator
}
}
}
该函数调用如下:
const iterableDataBatches: AsyncIterable<
SomeDataInterfaceNotGeneric[]
> = await getIterable() // function call
for await (const batchChunk of data) {
batchChunk.forEach(async data => {
// some operations
await this.publishChanges()
})
}
我收到此错误:
error TS2347: Untyped function calls may not accept type arguments.
我通过明确声明es6-promise来尝试this帖子上的解决方案,这会产生以下错误:
error TS2529: Duplicate identifier 'Promise'. Compiler reserves name 'Promise' in top level scope of a module containing async functions.
更新1 T不是通用类型,而是一种确定类型的数据。对困惑感到抱歉。
更新2
async findByCriteria<T>(
searchCriteria: SelectorQuery | {},
additionalQuery: AdditionalQueryInterface = {
sort: {},
limit: 0,
skip: 0
}
): Promise<T[]> {
const [sort, skip, limit] = [
additionalQuery.sort || {},
additionalQuery.skip || 0,
additionalQuery.limit || 0
]
const db = await this.dbPromise
return db
.collection(this.collectionName)
.find(searchCriteria)
.sort(sort)
.skip(skip)
.limit(limit)
.toArray()
}