0

I'm doing basic programming with js+html+css I want to create a simple webpage to represent Starwars movie ship details. Simply, each ship object which is returned upon the get request to the https://swapi.dev/api/starships/ consists of several strings and an array of URL where each URL will return another JSON where the title attribute of that JSON is the movie name. For example, one of the film URLs is https://swapi.dev/api/films/1/

Ok. I have successfully received all ships and their strings. But for the film part, I have a problem. To make the question short, this is the code I run to get my films:

for (let i=0;i<details[l].films.length;i++)
{
    var filmName = document.createElement("div");
    var s =getFilmName(details[l].films[i])
    alert("on retuern "+s+" type "+typeof(s))
    filmName.innerHTML=s
    rightContainer.appendChild(filmName)
}

where details[l].films is itself an array of URLs. right container is the container where I want to store and show the film names, but it's not important here.

function getFilmName(url) {
console.log(url+ " the url")
const Http = new XMLHttpRequest();
Http.open("GET", url);
Http.send();



Http.onreadystatechange = function (){
    if (this.status == 200 && this.readyState==4){

        response=JSON.parse(Http.responseText)
        let s=""
        s=s+response.title
        alert("s is "+s+ " "+typeof(s))
        alert(response.title+ " "+typeof (response.title) + " name and title ")
        return s

        }
    }
}

This function sends GET request to a single film URL, and parses and returns it's title. The problem now is that when I call getFilmName function on the top for loop, I get the return value undefined! and earlier than getFilmName receives the JSON and parses it. that is, getFilmName successfully receives the film name, but it's caller will continue executing and receives Undifined first, while a couple seconds later getFilmName correctly alerts the received film name. I even tried to make the GET request syncrhounous, by adding open("GET",URL,false) but it didn't work. How can I force the caller to wait until the result is ready and then move on?

m0ss
  • 334
  • 2
  • 4
  • 17

0 Answers0