Movie API: Promise Pending Issue

I’m using The Movie Database API. And the problem that i can’t solve is returning “keys” variable when i call the function with Movie’s id.I’m new on JavaScript that’s why i can’t solve this. Hope someone can help me, thanks in advance.

const APIURL = "https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=[MY API KEY HERE]&page-1";     
getMovies(APIURL)
async function getMovies(url)
{
    const resp = await fetch(url);
    const respData = await resp.json();
    showMovies(respData.results)
}
        async function getTrailer(id)
    {
         const resp = await fetch(`https://api.themoviedb.org/3/movie/${id}/videos?api_key=[MY API KEY HERE]&language=en-US`);
         const respDataa = await resp.json();
         let results = respDataa.results;
         let keys = results[0].key;
         return keys;
    }
    
    
    function showMovies(movies){
      movies.forEach(movie => {
           const modals = document.createElement('div');
         modals.classList.add('modal');
         modals.innerHTML = `  <a target="_blank" href ="https://www.youtube.com/watch?v=${getTrailer(movie.id)}">Watch Trailer</a>`

}

You have to await or.then the return (it’s a Promise). You also have syntax errors in the showMovies function.

function showMovies(movies) {
  // make the forEach callback async
  movies.forEach(async (movie) => {
    console.log(getTrailer(movie.id)) // Promise {<pending>}

    const trailer = await getTrailer(movie.id);
    console.log({ trailer });

    const modals = document.createElement("div");
    modals.classList.add("modal");
    modals.innerHTML = `  <a target="_blank" href ="https://www.youtube.com/watch?v=${trailer}">Watch Trailer</a>`;
  });
}
1 Like

Whoa thank you sir!! I’ve tried everything but i couldn’t find any solution for it.Thank you so much, you make my day :slight_smile:

1 Like