Home > Blockchain >  Javascript array assigning index value is not working
Javascript array assigning index value is not working

Time:07-03

I am facing this issue, enter image description hereconsole output contains 3 arrays, the first is on top (contains ids), the second is which contains the movies name based on that id, the third contains the movie poster, so the main thing is tag [11] before the first string that the other two arrays don't have [11], although there are 11 11 items in them. SO due to this, I am unable to fetch the first index i.e. titles[0] give an error while first array ids[0] give the first element. How I can overcome this issue

I also marked the output thanks Do not know how to deal with this.

<!DOCTYPE html>
    <html>
    <body>
    
        <div id="pred">
    
    
        </div>
    
    
        <script>
            let ids = "[19995, 440, 679, 17663, 602, 7450, 44943, 34851, 11551, 76757, 11260]"
            
            let data = JSON.parse(ids.replaceAll("\""))
            console.log(data)
            let titles = []
            let posters = []
            
            my_api_key = '34b55fa7f2d2346aa1045ed4cc22bd12'
            url1 = 'https://api.themoviedb.org/3/movie/'
            url2 = "https://image.tmdb.org/t/p/w500/" 
            for(i = 0 ; i < data.length ; i  ){
             url = url1   data[i]   '?api_key='   my_api_key;
            
            fetch(url).then((data)=>{
                return data.json();
            
            }).then((completedata)=>{
                titles.push(completedata.title);
                posters.push(url2   (completedata.poster_path));
            
            }).catch((err)=>{
                console.log(err)
            })
            
            }
            let my_M = "";
            my_M = `
            <h1 style="color:blue ;">
                    <span>${titles[0]}</span>
            </h1>
            `;
            document.getElementById("pred").innerHTML = my_M;
            
            console.log(titles)
            console.log(posters)
            </script>
    
    
    
    </body>
    
    </html>

CodePudding user response:

The reason why you are getting the {} as return for the last two console.log() is because your API fetch is not finished when you code reaches the console.log(titles) and console.log(posters) in the end. So the data which is coming after the fetch (inside then) is not yet available. This is called synchronously running code.

To make sure that the latter piece of code will 'wait' for the earlier piece we need to make the code asynchronously, you can read more about it in this enter image description here

CodePudding user response:

The issue is you are trying to access the titles before receiving the response from the API. In javascript we call it asynchronous code. You can make your code synchronous by waiting for its execution to finish. You can use async/await syntax to deal with this.

You can try running the below code snippet. You will see some delay on the console log.

Your fetch request API call is awaited using await. In order for you to use await inside a function, you need to add async keyword on the function.

<!DOCTYPE html>
    <html>
    <body>
    
        <div id="pred">
    
    
        </div>
    
    
        <script>
        async function fetchMoviesJSON(url) {
            const response = await fetch(url);
            const movies = await response.json();
            return movies;
        }
        
        async function fetchTitles() {
            let ids = "[19995, 440, 679, 17663, 602, 7450, 44943,                             34851, 11551, 76757, 11260]";
            
            let data = JSON.parse(ids.replaceAll("\""));

            let titles = [];
            let posters = [];
            
            const my_api_key = '34b55fa7f2d2346aa1045ed4cc22bd12';
            const url1 = 'https://api.themoviedb.org/3/movie/';
            const url2 = "https://image.tmdb.org/t/p/w500/" ;
            for (i = 0 ; i < data.length ; i  ) {
                url = url1   data[i]   '?api_key='   my_api_key;
                try {
                  const movieResponse = await fetchMoviesJSON(url);
                  titles.push(movieResponse.title);
                  posters.push(url2   (movieResponse.poster_path));
                } catch (err) {
                  console.log(err);
                }
                const my_M = `
                <h1 style="color:blue ;">
                        <span>${titles[0]}</span>
                </h1>
                `;
                document.getElementById("pred").innerHTML = my_M;
            }
            console.log(titles);
            console.log(posters)
        }
        fetchTitles()
      </script>
    
    
    
    </body>
    
    </html>

  • Related