0

Context: I'm building a popup widget. The html and css files are stored in S3. I need to get those files asynchronously and then continue with the rest of the logic.

In the code below, I'm getting the html file from S3 and setting the contents of a popup div to be equal to the contents of this file.

The issue: I have a lot more logic to handle the rest of the form. I'm currently using loadFormFunctions as the starting point to executing the remaining logic. loadFormFunctions contains many other functions that need to be executed.

Question: Is this best practice for executing the remaining code? Or is there a way to check if getFromS3 has resolved and then continue executing another function?

async function getFromS3() {

    await fetch('someFileinS3.html', {
    }).then((response) => {
        return response.text()

    }).then((text) => {
        popup.innerHTML = "";
        popup.innerHTML = text;
        loadFormFunctions();
    })

}

I realize the way I've laid this out might be confusing. Please let me know if you need me to rephrase.

1
  • Besides using await and storing in local variables instead of using then, I do not know. This question looks like a good fit for Code Review.
    – Theraot
    Feb 3, 2020 at 6:11

2 Answers 2

1

Your code seems unnecessarily verbose. You don't need to use continuations (then) for this when you have async await available to you. You also really don't need a whole separate continuation just to get the text from the response object.You're also redundantly setting popup.innerHTML to an empty string before just reassigning it again.

How about the following?

async function getFromS3() {
    response = await fetch('someFileinS3.html');
    popup.innerHTML = response.text();
    loadFormFunctions();
}
1
  • Thanks! That looks much simpler. Just to confirm, is it bad practice to use loadFormFunctions as the starting point to executing the rest of the program? The program currently works fine, I'm just curious to know if this is the way you would go about doing it. Feb 6, 2020 at 20:36
0

In your current code there is no need to use async/await, you can just return the top fetch

And then you can just

await getFromS3()

in your code and then continue on with the rest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.