0
fetch("/text").then(function(response){                     
    response.text().then(function(text){                    
        addWords(text.split(" "))                           
    })                                                      
})                                                          
                                       
words = document.getElementById("parent").children;

I make a GET request using fetch, and then I call a function (addWords(text.split(" "))) which simply just takes an array of text as an arguement and places that text into a div inside a parent div that has an id of "parent".

However, right after, when I attempted to select the children of said parent div, I receive the following error. It seems the issue is that the elements are not loaded into "parent" when I try to grab them.

How can I pause execution, until the text is fully loaded, before trying to grab it?

Image: Browser error message

  • https://stackoverflow.com/questions/14455293/how-and-when-to-use-async-and-await or https://stackoverflow.com/questions/22442321/callback-function-example/48333938 – Will Feb 07 '21 at 22:14

1 Answers1

0

You can use Async/Await construction instead of Promise to fetch response. After getting response, you can do whatever you need.