简体   繁体   中英

How can I handle the promise rejection with a filter inside?

So I'm trying to build an autocomplete searchbar to filter by name or id, data gets fetched from a JSON (data.json) with several pokemons.

Here is a part of the JSON:

{ 
    "1" :{"id": "1", "name": "bulbasaur"}, 
    "2" :{"id": "2", "name": "ivysaur"}, 
    "3" :{"id": "3", "name": "venusaur"}, 
    "4" :{"id": "4", "name": "charmander"}, 
    "5" :{"id": "5", "name": "charmeleon"}
} 

and here is the JS code:

const search = document.querySelector('#search-bar');

const searchPokemon = async searchText => {
    const res = await fetch('./data.json')
    const pokemons = await res.json();  
    
    // Get matches
    let matches = pokemons.filter(pokemon => {
        const regexp = new RegExp(`^${searchText}`, 'gi');
        return pokemon.name.match(regexp) || pokemon.id.match(regexp);
    });
    console.log(matches);
}

search.addEventListener('input', () => searchPokemon(search.value));

I want to get the matches on the console but I get an Unhandled Promise Rejection error. I tried a try...catch but I still get errors. Anyone who can point me in the right direction? Thanks.

Don't put the console.log effect inside of your search function, return the value instead -

async function searchPokemon(searchText) {
  const res = await fetch('./data.json')
  const pokemons = await res.json()
  const regexp = new RegExp(`^${searchText}`, 'gi')  

  if (pokemons == null)
    return []
  else
    return pokemons.filter(pokemon =>
      pokemon.name.match(regexp) || pokemon.id.match(regexp)
    )
}

Put the effect in your event listener. console.log or searchResultElement.appendChild(...) -

const search = document.querySelector('#search-bar');

search.addEventListener('input', async event => {
  try {
    const pokemons = await searchPokemon(search.value)
    console.log("got pokemons", pokemons)
  }
  catch (err) {
    console.error("An error occurred", err)
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM