1- const retry = require ( 'retry' )
1+ const { RetryOperation } = require ( './ retry' )
22
3- const isRetryError = ( err ) => err ?. code === 'EPROMISERETRY' && Object . hasOwn ( err , 'retried' )
3+ const createTimeout = ( attempt , opts ) => Math . min ( Math . round ( ( 1 + ( opts . randomize ? Math . random ( ) : 0 ) ) * Math . max ( opts . minTimeout , 1 ) * Math . pow ( opts . factor , attempt ) ) , opts . maxTimeout )
4+ const isRetryError = err => err ?. code === 'EPROMISERETRY' && Object . hasOwn ( err , 'retried' )
45
5- async function promiseRetry ( fn , options = { } ) {
6- const operation = retry . operation ( options )
6+ const promiseRetry = async ( fn , options = { } ) => {
7+ let timeouts = [ ]
8+ if ( options instanceof Array ) {
9+ timeouts = [ ...options ]
10+ } else {
11+ if ( options . retries === Infinity ) {
12+ options . forever = true
13+ delete options . retries
14+ }
15+ const opts = {
16+ retries : 10 ,
17+ factor : 2 ,
18+ minTimeout : 1 * 1000 ,
19+ maxTimeout : Infinity ,
20+ randomize : false ,
21+ ...options
22+ }
23+ if ( opts . minTimeout > opts . maxTimeout ) {
24+ throw new Error ( 'minTimeout is greater than maxTimeout' )
25+ }
26+ if ( opts . retries ) {
27+ for ( let i = 0 ; i < opts . retries ; i ++ ) {
28+ timeouts . push ( createTimeout ( i , opts ) )
29+ }
30+ // sort the array numerically ascending (since the timeouts may be out of order at factor < 1)
31+ timeouts . sort ( ( a , b ) => a - b )
32+ } else if ( options . forever ) {
33+ timeouts . push ( createTimeout ( 0 , opts ) )
34+ }
35+ }
36+
37+ const operation = new RetryOperation ( timeouts , {
38+ forever : options . forever ,
39+ unref : options . unref ,
40+ maxRetryTime : options . maxRetryTime
41+ } )
742
843 return new Promise ( function ( resolve , reject ) {
944 operation . attempt ( async number => {
@@ -13,13 +48,12 @@ async function promiseRetry (fn, options = {}) {
1348 } , number , operation )
1449 return resolve ( result )
1550 } catch ( err ) {
16- if ( isRetryError ( err ) ) {
17- if ( operation . retry ( err . retried || new Error ( ) ) ) {
18- return
19- }
51+ if ( ! isRetryError ( err ) ) {
52+ return reject ( err )
53+ }
54+ if ( ! operation . retry ( err . retried || new Error ( ) ) ) {
2055 return reject ( err . retried )
2156 }
22- return reject ( err )
2357 }
2458 } )
2559 } )
0 commit comments