@@ -50,41 +50,45 @@ const addLocaleParam = (url, lang) => {
5050
5151// Tries to fetch 1 + retryCount times until 200 is returned.
5252// Uses retryDelay (ms) between requests. url and options are normal fetch parameters
53- export const retryFetch = (
53+ // eslint-disable-next-line consistent-return
54+ export const retryFetch = async (
5455 URL ,
5556 options = { } ,
5657 retryCount ,
5758 retryDelay ,
5859 config = { } ,
5960) => {
60- return new Promise ( ( resolve , reject ) => {
61- const retry = retriesLeft => {
62- fetch ( URL , {
63- ...options ,
64- headers : addSubscriptionHeader ( options . headers , config ) ,
65- } )
66- . then ( res => {
67- if ( res . ok ) {
68- resolve ( res ) ;
69- // Don't retry if user is not logged in
70- } else if ( res . status === 401 ) {
71- throw res . status ;
72- } else {
73- // eslint-disable-next-line no-throw-literal
74- throw `${ URL } : ${ res . statusText } ` ;
75- }
76- } )
77- . catch ( async err => {
78- if ( retriesLeft > 0 && err !== 401 ) {
79- await delay ( retryDelay ) ;
80- retry ( retriesLeft - 1 ) ;
81- } else {
82- reject ( err ) ;
83- }
84- } ) ;
85- } ;
86- retry ( retryCount ) ;
87- } ) ;
61+ options = {
62+ ...options ,
63+ headers : addSubscriptionHeader ( options . headers , config ) ,
64+ } ;
65+
66+ let retriesLeft = retryCount ;
67+ while ( retriesLeft >= 0 ) {
68+ try {
69+ // eslint-disable-next-line no-await-in-loop
70+ return await fetchWithErrors ( URL , options ) ;
71+ } catch ( error ) {
72+ if ( ! ( error instanceof FetchError ) ) {
73+ // Throwing unrelated errors (e.g. TypeError) allows us to catch bugs.
74+ throw error ;
75+ }
76+
77+ if ( error . res . status === 401 ) {
78+ // todo: throw `error` instead of a literal (breaking change)
79+ // eslint-disable-next-line no-throw-literal
80+ throw 401 ;
81+ }
82+ if ( retriesLeft === 0 ) {
83+ // todo: throw `error` instead of a literal (breaking change)
84+ // eslint-disable-next-line no-throw-literal
85+ throw `${ URL } : ${ error . res . statusText } ` ;
86+ }
87+ retriesLeft -= 1 ;
88+ // eslint-disable-next-line no-await-in-loop
89+ await delay ( retryDelay ) ;
90+ }
91+ }
8892} ;
8993
9094/**
0 commit comments