From 68242b72753814575cec542e078d19eb28c043bc Mon Sep 17 00:00:00 2001 From: Jarda Snajdr Date: Thu, 8 Oct 2020 15:56:29 +0200 Subject: [PATCH] block-directory: simplify the loadAssets flow by making it an async function --- .../block-directory/src/store/controls.js | 51 ++++++++----------- 1 file changed, 20 insertions(+), 31 deletions(-) diff --git a/packages/block-directory/src/store/controls.js b/packages/block-directory/src/store/controls.js index a5ee96d8e6c9d..6ddb9c0e6ac47 100644 --- a/packages/block-directory/src/store/controls.js +++ b/packages/block-directory/src/store/controls.js @@ -62,47 +62,36 @@ export function loadAssets( assets ) { } const controls = { - LOAD_ASSETS() { + async LOAD_ASSETS() { /* * Fetch the current URL (post-new.php, or post.php?post=1&action=edit) and compare the * Javascript and CSS assets loaded between the pages. This imports the required assets * for the block into the current page while not requiring that we know them up-front. * In the future this can be improved by reliance upon block.json and/or a script-loader - * dependancy API. + * dependency API. */ - return apiFetch( { + const response = await apiFetch( { url: document.location.href, parse: false, - } ) - .then( ( response ) => response.text() ) - .then( ( data ) => { - const doc = new window.DOMParser().parseFromString( - data, - 'text/html' - ); + } ); + + const data = await response.text(); + + const doc = new window.DOMParser().parseFromString( data, 'text/html' ); - const newAssets = Array.from( - doc.querySelectorAll( 'link[rel="stylesheet"],script' ) - ).filter( - ( asset ) => - asset.id && ! document.getElementById( asset.id ) - ); + const newAssets = Array.from( + doc.querySelectorAll( 'link[rel="stylesheet"],script' ) + ).filter( + ( asset ) => asset.id && ! document.getElementById( asset.id ) + ); - return new Promise( async ( resolve, reject ) => { - for ( const i in newAssets ) { - try { - /* - * Load each asset in order, as they may depend upon an earlier loaded script. - * Stylesheets and Inline Scripts will resolve immediately upon insertion. - */ - await loadAsset( newAssets[ i ] ); - } catch ( e ) { - reject( e ); - } - } - resolve(); - } ); - } ); + /* + * Load each asset in order, as they may depend upon an earlier loaded script. + * Stylesheets and Inline Scripts will resolve immediately upon insertion. + */ + for ( const newAsset of newAssets ) { + await loadAsset( newAsset ); + } }, };