javascript - 如何处理带有过滤器的承诺拒绝?
问题描述
所以我正在尝试构建一个自动完成搜索栏来按名称或 ID 进行过滤,数据是从带有几个口袋妖怪的 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));
我想在控制台上获取匹配项,但出现未处理的 Promise Rejection 错误。我尝试了尝试...catch,但仍然出现错误。谁能指出我正确的方向?谢谢。
解决方案
不要将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.log
或searchResultElement.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)
}
})