diff --git a/src/cursor/abstract_cursor.ts b/src/cursor/abstract_cursor.ts index 8d069787cb0..a9246398cd4 100644 --- a/src/cursor/abstract_cursor.ts +++ b/src/cursor/abstract_cursor.ts @@ -281,8 +281,8 @@ export abstract class AbstractCursor< } /** Returns current buffered documents */ - readBufferedDocuments(number?: number): TSchema[] { - const bufferedDocs: TSchema[] = []; + readBufferedDocuments(number?: number): NonNullable[] { + const bufferedDocs: NonNullable[] = []; const documentsToRead = Math.min( number ?? this.documents?.length ?? 0, this.documents?.length ?? 0 @@ -457,29 +457,33 @@ export abstract class AbstractCursor< * results when this cursor had been previously accessed. In that case, * cursor.rewind() can be used to reset the cursor. */ - async toArray(): Promise { + async toArray(transform_temp?: (doc: TSchema) => any): Promise { const array: TSchema[] = []; - // when each loop iteration ends,documents will be empty and a 'await (const document of this)' will run a getMore operation + this.transform = transform_temp; + // at the end of the loop (since readBufferedDocuments is called) the buffer will be empty + // then, the 'await of' syntax will run a getMore call for await (const document of this) { array.push(document); - let docs = this.readBufferedDocuments(); + const docs = this.readBufferedDocuments(); if (this.transform != null) { - docs = await Promise.all( - docs.map(async doc => { - if (doc != null) { - return await this.transformDocument(doc); - } else { - throw Error; - } - }) - ); + for (const doc of docs) { + array.push(await this.transformDocument(doc)); + } + } else { + array.push(...docs); } - array.push(...docs); } return array; } + async toArrayOld(): Promise { + const array = []; + for await (const document of this) { + array.push(document); + } + return array; + } /** * Add a cursor flag to the cursor * @@ -820,7 +824,7 @@ export abstract class AbstractCursor< } /** @internal */ - private async transformDocument(document: NonNullable): Promise { + private async transformDocument(document: NonNullable): Promise> { if (this.transform == null) return document; try {