import * as retrier from "retry" ; import { OperationOptions , RetryOperation } from "retry" ; export const retry = ( fn , opts ) => { const run = ( resolve , reject ) => { const options = opts || { } ; let op ; if ( ! ( "randomize" in options ) ) { options . randomize = true ; } op = retrier . operation ( options ) ; function bail ( err ) { reject ( err || new Error ( "Aborted" ) ) ; } function onError ( err , num ) { if ( err . bail ) { bail ( err ) ; return ; } if ( ! op . retry ( err ) ) { reject ( op . mainError ( ) ) ; } } function runAttempt ( num ) { let val ; try { val = fn ( bail , num ) ; } catch ( err ) { onError ( err , num ) ; return ; } Promise . resolve ( val ) . then ( resolve ) . catch ( function catchIt ( err ) { onError ( err , num ) ; } ) ; } op . attempt ( runAttempt ) ; } ; return new Promise ( run ) ; } ;