1

I am trying to understand and implement promises using javascript. I have a searchMovies function that takes in the searchInput, filters the text and checks if that movie name is present in movies Array. I would like to display the result in resultContainer. I am able to read the text entered in input box and pass it to SearchMovies function but not sure how to handle the promise resolve and reject. How shall I use the output of promise and assign it to resultsContainer?

class MovieSearch {
  constructor(searchInput, resultsContainer) {
    this.searchInput = searchInput;
    this.resultsContainer = resultsContainer;
  }

  //helper function to debounce (only call it after there has been a "cool off" period) a function
  _debounce(fn) {
    let timeout = undefined;
    return (...args) => {
      if (timeout) {
        clearTimeout(timeout);
      }

      timeout = setTimeout(() => {
        fn(...args);
      }, 200);
    };
  }
}

// use this function to search the movie.
function searchMovies(searchText) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const regex = new RegExp(`${searchText}`, "i");
      try {
        resolve(movies.filter((movie) => regex.test(movie)));
      } catch (e) {
        reject(e);
      }
    }, 800);
  });
}

const search = new MovieSearch(
        document.querySelector(".search-input"), //input text area
        document.querySelector(".search-results") //display the result here
);

//call searchMovies and pass the input entered in text box
var progress = search._debounce(searchMovies)
search.searchInput.addEventListener('input', function(){
    progress(search.searchInput.value);
    
});

const movies = [
  "Nomadland",
  "Minari",
  "Judas and the Black Messiah",
  "The Trial of the Chicago 7",
];

At what point should I assign the result to resultContainer ? Do I need to call SearchMovies function twice ?

user2128
  • 590
  • 2
  • 13
  • 35
  • I am confused as to how to call searchMovies().then as i have already assigned it under debounce. I know that debounce won't accept .thn() within it. – user2128 Jun 24 '21 at 04:47
  • 1
    Instead of `search._debounce(searchMovies)`, how about `search._debounce(searchTerm => searchMovies(searchTerm).then(whatever))`? [How to use debounce on async function?](https://stackoverflow.com/questions/50837291/how-to-use-debounce-on-async-function) might be worth a peek. – ggorlen Jun 24 '21 at 05:53

0 Answers0