file import { BeidouError } from './error' ; import { SyncPromise } from './syncpromise' ; /** A simple queue that holds promises. */ export class PromiseBuffer < T > { /** Internal set of queued Promises */ private readonly _buffer : Array < PromiseLike < T > > = [ ] ; public constructor ( protected _limit ? ) { } /**
     * Says if the buffer is ready to take more requests
     */ public isReady ( ) { return this . _limit === undefined || this . length ( ) < this . _limit ; } public add ( task ) { if ( ! this . isReady ( ) ) { return SyncPromise . reject ( new BeidouError ( 'Not adding Promise due to buffer limit reached.' ) ) ; } if ( this . _buffer . indexOf ( task ) === - 1 ) { this . _buffer . push ( task ) ; } task . then ( ( ) => this . remove ( task ) ) . then ( null , ( ) => this . remove ( task ) . then ( null , ( ) => { } ) ) ; return task ; } param task returns public remove ( task ) { const removedTask = this . _buffer . splice ( this . _buffer . indexOf ( task ) , 1 ) [ 0 ] ; return removedTask ; } /**
     * This function returns the number of unresolved promises in the queue.
     */ public length ( ) { return this . _buffer . length ; } public drain ( timeout ? ) { return new SyncPromise < boolean > ( resolve => { const capturedSetTimeout = setTimeout ( ( ) => { if ( timeout && timeout > 0 ) { resolve ( false ) ; } } , timeout ) ; SyncPromise . all ( this . _buffer ) . then ( ( ) => { clearTimeout ( capturedSetTimeout ) ; resolve ( true ) ; } ) . then ( null , ( ) => { resolve ( true ) ; } ) ; } ) ; } }