I think you really need to work on re-usability and program flow of your methods, there are some things wrong that make it hard to guess what is going on without having a complete example, but I do have a suggested rewrite that gives you an indication how you could refactor it
function getData( url ) {
return fetch( url )
.then( response => {
if ( response.ok ) {
// return the response itself
return response;
}
// well the response wasn't okay, throw an error, break the chain
throw '400 Bad request';
});
}
function replaceContentWithEnumText( url, enumText ) {
return getData( url )
// valid data, we want the response as text
.then( resp => resp.text() )
// split the text (if any, and join it with enumText)
.then( text => {
return text && text.split( '$enum' ).join( enumText );
} );
}
// note for here it isn't a valid url, so you really wont see anything)
replaceContentWithEnumText( '/assets/groovy.txt', 'someText' )
// once in the below then, fetch has happened, your text was replaced, you can use replacedContent
.then( replacedContent => console.log( 'comleted succesfully, data returned would be ', replacedContent ) )
// something went wrong in the entire chain of events, handling it here makes sense
.catch( err => console.log( 'error occured', err ) );
If I would go through your original code, for me:
- I dislike having magical global variables, that get mutated, they really don't help you, you never really know what their state would be...
- Your function is written with a capital letter, although that could be a guideline, a convention would give funtions lowercased letters to start with
- You assign
let data
to await fetch...
, at most, data would contain the error message there, because only from the catch block you are actually returning something
- You don't seem to do anything with the
let data
variable
- In your promise chain, you then have a
data
argument (confusing)
- Your
async/await
is completely superfluous, your code doesn't even use it (I know you believe await
makes your code synchronous, but well, it's not working as you think it is)
async
marked functions will implicitly return a promise. You can await
promises, which will then return the response of the promise chain to what ever you assign it. Your code will wait to continue, until the promise runs through (but, not your program, that will continue running).
It is really just syntactic sugar for promises, some say it makes it more readable, but that is entirely opinion based.