如何使用内部过滤器处理承诺拒绝?

时间:2021-06-18 10:57:23

标签: javascript json promise

因此,我正在尝试构建一个自动完成搜索栏以按名称或 ID 进行过滤,数据是从包含多个 pokemon 的 JSON (data.json) 中获取的。

这是 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"}
} 

这是JS代码:

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));

我想在控制台上获取匹配项,但收到未处理的承诺拒绝错误。我尝试了 try...catch 但我仍然遇到错误。谁能指出我正确的方向?谢谢。

1 个答案:

答案 0 :(得分:-1)

不要将 console.log 效果放在 search 函数中,而是将 return 值 -

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

const searchPokemon = async searchText => {
    const res = await fetch('./data.json')
    const pokemons = await res.json()
    
    if (pokemons == null)
      return []
    else
      return pokemons.filter(pokemon => {
        const regexp = new RegExp(`^${searchText}`, 'gi')
        return pokemon.name.match(regexp) || pokemon.id.match(regexp)
      })
}

将效果放入您的事件侦听器中。 console.logsearchResultElement.appendChild(...) -

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)
  }
})