import { safelyCallBack } from "./safelyCallBack" ; export class MessageRunner { private _message : string ; private _handlers : Function [ ] ; private _callback : Function ; private constructor ( message , handlers , callback ) { this . _message = message ; this . _handlers = handlers ; this . _callback = callback ; } private public run ( ) { this . next ( ) ; } private next ( ) { let handler ; while ( this . _handlers . length > 0 ) { handler = this . _handlers . pop ( ) ; if ( handler . length === 0 ) { handler ( ) ; } else if ( handler . length === 1 ) { handler ( this . _message ) ; } else if ( handler . length === 2 ) { let handled = false ; handler ( this . _message , ( error = null , msg = null ) : void => { if ( handled ) { return ; } handled = true ; if ( error || this . _handlers . length === 0 ) { if ( this . _callback ) { safelyCallBack ( this . _callback , error , this . _message ) ; } } else { this . next ( ) ; } } ) ; return ; } else { throw new Error ( "Bad handler signature" ) ; } } if ( this . _callback ) { safelyCallBack ( this . _callback , null , this . _message ) ; } } }