11import { SentryError } from './error' ;
2- import { SyncPromise } from './syncpromise' ;
3-
4- function allPromises < U = unknown > ( collection : Array < U | PromiseLike < U > > ) : PromiseLike < U [ ] > {
5- return new SyncPromise < U [ ] > ( ( resolve , reject ) => {
6- if ( collection . length === 0 ) {
7- resolve ( null ) ;
8- return ;
9- }
10-
11- let counter = collection . length ;
12- collection . forEach ( item => {
13- void SyncPromise . resolve ( item )
14- . then ( ( ) => {
15- // eslint-disable-next-line no-plusplus
16- if ( -- counter === 0 ) {
17- resolve ( null ) ;
18- }
19- } )
20- . then ( null , reject ) ;
21- } ) ;
22- } ) ;
23- }
2+ import { rejectedSyncPromise , resolvedSyncPromise , SyncPromise } from './syncpromise' ;
243
254export interface PromiseBuffer < T > {
265 // exposes the internal array so tests can assert on the state of it.
@@ -63,7 +42,7 @@ export function makePromiseBuffer<T>(limit?: number): PromiseBuffer<T> {
6342 */
6443 function add ( taskProducer : ( ) => PromiseLike < T > ) : PromiseLike < T > {
6544 if ( ! isReady ( ) ) {
66- return SyncPromise . reject ( new SentryError ( 'Not adding Promise due to buffer limit reached.' ) ) ;
45+ return rejectedSyncPromise ( new SentryError ( 'Not adding Promise due to buffer limit reached.' ) ) ;
6746 }
6847
6948 // start the task and add its promise to the queue
@@ -94,7 +73,13 @@ export function makePromiseBuffer<T>(limit?: number): PromiseBuffer<T> {
9473 * `false` otherwise
9574 */
9675 function drain ( timeout ?: number ) : PromiseLike < boolean > {
97- return new SyncPromise < boolean > ( resolve => {
76+ return new SyncPromise < boolean > ( ( resolve , reject ) => {
77+ let counter = buffer . length ;
78+
79+ if ( ! counter ) {
80+ return resolve ( true ) ;
81+ }
82+
9883 // wait for `timeout` ms and then resolve to `false` (if not cancelled first)
9984 const capturedSetTimeout = setTimeout ( ( ) => {
10085 if ( timeout && timeout > 0 ) {
@@ -103,9 +88,14 @@ export function makePromiseBuffer<T>(limit?: number): PromiseBuffer<T> {
10388 } , timeout ) ;
10489
10590 // if all promises resolve in time, cancel the timer and resolve to `true`
106- void allPromises ( buffer ) . then ( ( ) => {
107- clearTimeout ( capturedSetTimeout ) ;
108- resolve ( true ) ;
91+ buffer . forEach ( item => {
92+ void resolvedSyncPromise ( item ) . then ( ( ) => {
93+ // eslint-disable-next-line no-plusplus
94+ if ( ! -- counter ) {
95+ clearTimeout ( capturedSetTimeout ) ;
96+ resolve ( true ) ;
97+ }
98+ } , reject ) ;
10999 } ) ;
110100 } ) ;
111101 }
0 commit comments