-1

I just fetch some resource from a page, and I put them into an array. Below is my code.

fetch(jsonUrl, {method: "get"})
.then((response) =>{
    return response.json();
}).then((data) =>{
    jsonData= data.result.results;
    
    for(let i = 0; i<jsonData.length; i++){
        place=[jsonData[i]["stitle"],jsonData[i]["file"].substring(0,end+3)];
        end=jsonData[i]["file"].toLowerCase().indexOf("jpg", 0);
        console.log(jsonData[i]["file"].substring(0,end+3));
        console.log(place);
        console.log(typeof(place));
        console.log(place[0]);
    }
})

The question is, I want to use it outside the fetch scope like this.

 let myDiv = document.getElementById("description");
 let newDiv = document.createElement("div");
 let textNode = document.createTextNode(place[0]);
 newDiv.appendChild(textNode);
 myDiv.appendChild(newDiv);

But the value of place would be "undefined". What should I do?

  • 2
    So why is the code not inside the block or you call a function when you have the data? This is the basics of asynchronous programming. – epascarello Oct 03 '22 at 16:07

1 Answers1

0

You have two code blocks and it's not clear the order that they are called in. Given that, the best answer I can give you is to make your second code block a function

 function addPlace(place) {
   let myDiv = document.getElementById("description");
   let newDiv = document.createElement("div");
   let textNode = document.createTextNode(place); // changed place[0] to place
   newDiv.appendChild(textNode);
   myDiv.appendChild(newDiv);
 }

Then you can call addPlace from your first code block using place[0] as your function parameter

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80