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 ?