1

I am trying to create an application that gets data from an API using fetch but whenever I try to pass the result to another function , the promise result is undefined. The promise result should return an Array of 10 movies.

//search through TV Maze library
const form = document.querySelector("#searchForm");
form.addEventListener("submit", (e) => {
  e.preventDefault();
});

const printMovieData = async function () {
  const queryString = "suits";
  const moviesImg = Promise.resolve(getMovieData(queryString));
  console.log(moviesImg);
};

const getMovieData = function (query) {
  fetch(`https://api.tvmaze.com/search/shows?q=${query}`)
    .then((res) => {
      const movieData = res.json();
      //console.log(movieData);
      return movieData;
    })
    .catch((error) => {
      console.log(error);
    });
};

printMovieData();

I have also tried using await instead of Promise.resolve but still the return is undefined.

This is my current console output

Samip
  • 48
  • 1
  • 6
  • 3
    you're not returning from your `getMovieData` function, only your callback, use: `return fetch(` instead, and then use `.then()` or `await` on the returned Promise (not Promise.resolve()) – Nick Parsons Sep 03 '21 at 03:49

1 Answers1

0

i think you have error when using async/await. You can try:

 const printMovieData = async function () {
    const queryString = "suits";
    const moviesImg = await getMovieData(queryString);
  console.log(moviesImg);
};

const getMovieData = async function (query) {
  try {
    const res = await fetch(`https://api.tvmaze.com/search/shows?q=${query}`);
    const movieData = await res.json();
    return movieData;
  } catch (error) {
    console.log(error);
  }
};

printMovieData();
hoangtd
  • 198
  • 2
  • 9