javascript异步并等待事件侦听器:宠物小精灵 [英] javascript async and await event listener: Pokemon

查看:91
本文介绍了javascript异步并等待事件侦听器:宠物小精灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过我自己进行的API练习来探索自己的方式,并且想知道为什么"id"会变成我"吗?元素不断向其中添加不必要的值.例如,我将搜索皮卡丘"首先,整个结果将返回皮卡丘(data.id为25)及其统计数据.点击下一个按钮(事件侦听器)后,id成功增加到列表中的下一个口袋妖怪Raichu(data.id为26);其统计信息也可以正确显示.这种情况完美地起作用了!

I am working my way through an API exercise I made on my own and was wondering why the "id" element keeps adding unnecessary values to it. For example, I would search "Pikachu" first and the whole result would return Pikachu (data.id is 25) and it's stats. After hitting the next button (event listener), the id gets successfully incremented to the next Pokemon on the list, Raichu (data.id is 26); its stats also show correctly. That condition works perfectly!

然后,我将搜索另一个口袋妖怪"Charmander",并且id值现在为"4".但是,问题是在我进行第二次搜索然后点击下一步"后开始的.再按一次.该ID将从Raichu的ID开始,然后将进一步递增,同时也从"4"递增.也一样因此,我的控制台日志开始看起来像这样:"4","27","5","28","6".在第二次搜索后每按一次,并没有弹出Charizard,而是在Raichu之后弹出了几只宠物小精灵.

Then I would search a different pokemon, "Charmander" and the id value is now "4". However, the problem starts after I do that second search and then hitting the "next" button again. The ID would start off at Raichu's ID and then it'll increment up further, while also incrementing from "4" as well. So my console log started to look like this: "4","27","5","28","6" after each press after the second search, and instead of having Charizard popping up, a few pokemon's after Raichu pop up.

我声明的内容有误还是写得太复杂?我想我期待的是"id"每次我搜索神奇宝贝时都会刷新该变量,但似乎它一直在运行.

Am I declaring things incorrectly or writing this too complex? I think I was expecting the "id" variable to refresh everytime I search for a pokemon but it seems like it is keeping it going.


function pokemonInfo(e) { 
                   e.preventDefault();
                    const searchValue = search.value
                    fetch(`https://pokeapi.co/api/v2/pokemon/${searchValue}`)
                    .then(res=>res.json())
                    .then(data => {
                        const pokemon = data
                        console.log(pokemon)
                        let id = pokemon.id
                        console.log(id)


                        next.addEventListener('click', ()=>{
                            id++
                            console.log(id)
                            fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
                            .then(res=>res.json())
                            .then(data => {
                            const pokemon = data
                            pokeName(pokemon);
                            sprtFrnt(pokemon);
                            sprtBck(pokemon);
                            firstType(pokemon);
                            secondType(pokemon);

                        })
                    })
                    
                        //Other Functions
                        pokeName(pokemon);
                        sprtFrnt(pokemon);
                        sprtBck(pokemon);
                        firstType(pokemon);
                        secondType(pokemon);
                        
                    })
                    .catch(err => {
                        const notFound ='This Pokemon is not found!'
                    })
                }




推荐答案

正在发生的事情是,每次进行新搜索时,都会在下一个按钮上添加新的事件侦听器.您应该将id的值保存在函数范围之外,并且只应将事件侦听器添加到next按钮一次.

What's happening is that every time you make a new search, you're adding a new event listener on the next button. You should be saving the value of id outside of the scope of your function and you should only add the event listener to the next button once.

您的代码似乎也可以重复很多次

Your code also seems to repeat itself a lot

这样的事情可以避免重复,并阻止您添加额外的侦听器:

Something like this would avoid repetition and stop you from adding extra listeners:

const ENDPOINT = 'https://pokeapi.co/api/v2/pokemon/';
let id = 1;

// Code where you define what next and search are ...

next.addEventListener('click', ()=>{
    fetchNewPokemon(id + 1);
});

function pokemonInfo(e) { 
    e.preventDefault();
    fetchNewPokemon(search.value);
}

function fetchNewPokemon(searchValue) {
    fetch(`${ENDPOINT}${searchValue}`)
        .then(res=>res.json())
        .then(pokemon => {
            id = pokemon.id;
            //Other Functions
            pokeName(pokemon);
            sprtFrnt(pokemon);
            sprtBck(pokemon);
            firstType(pokemon);
            secondType(pokemon);
            
        })
        .catch(err => {
            const notFound ='This Pokemon is not found!'
        })
}

阅读范围/闭包可能有助于您理解为什么代码未按预期运行的原因. MDN撰写了大量有关关闭以及如何嵌套它们的文章影响您的代码.

Reading up on scope/closures might help you understand why it is that your code wasn't working the way you expected it to. MDN has a great write up about Closures and how nesting them impacts your code.

这篇关于javascript异步并等待事件侦听器:宠物小精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆