From ee368549cdf193debbc81c93677be3583dc6e3c9 Mon Sep 17 00:00:00 2001 From: Jarda Snajdr Date: Wed, 2 Sep 2020 10:50:43 +0200 Subject: [PATCH] api-fetch: simplify the code that executes the handlers (#24999) * apiFetch: simplify the promise-chaining code * Use reduce(Right) to compose middlewares --- packages/api-fetch/src/index.js | 48 ++++++++++++++------------------- 1 file changed, 20 insertions(+), 28 deletions(-) diff --git a/packages/api-fetch/src/index.js b/packages/api-fetch/src/index.js index b9fe1a6d0875aa..a77a6295637a96 100644 --- a/packages/api-fetch/src/index.js +++ b/packages/api-fetch/src/index.js @@ -120,36 +120,28 @@ function setFetchHandler( newFetchHandler ) { } function apiFetch( options ) { - const steps = [ ...middlewares, fetchHandler ]; - - const createRunStep = ( index ) => ( workingOptions ) => { - const step = steps[ index ]; - if ( index === steps.length - 1 ) { - return step( workingOptions ); + // creates a nested function chain that calls all middlewares and finally the `fetchHandler`, + // converting `middlewares = [ m1, m2, m3 ]` into: + // ``` + // opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) ); + // ``` + const enhancedHandler = middlewares.reduceRight( ( next, middleware ) => { + return ( workingOptions ) => middleware( workingOptions, next ); + }, fetchHandler ); + + return enhancedHandler( options ).catch( ( error ) => { + if ( error.code !== 'rest_cookie_invalid_nonce' ) { + return Promise.reject( error ); } - const next = createRunStep( index + 1 ); - return step( workingOptions, next ); - }; - - return new Promise( ( resolve, reject ) => { - createRunStep( 0 )( options ) - .then( resolve ) - .catch( ( error ) => { - if ( error.code !== 'rest_cookie_invalid_nonce' ) { - return reject( error ); - } - - // If the nonce is invalid, refresh it and try again. - window - .fetch( apiFetch.nonceEndpoint ) - .then( checkStatus ) - .then( ( data ) => data.text() ) - .then( ( text ) => { - apiFetch.nonceMiddleware.nonce = text; - apiFetch( options ).then( resolve ).catch( reject ); - } ) - .catch( reject ); + // If the nonce is invalid, refresh it and try again. + return window + .fetch( apiFetch.nonceEndpoint ) + .then( checkStatus ) + .then( ( data ) => data.text() ) + .then( ( text ) => { + apiFetch.nonceMiddleware.nonce = text; + return apiFetch( options ); } ); } ); }