简体   繁体   English

仅在第二次点击时获取

[英]fetching only in the second click

i have a problem on my fetching.我的取物有问题。 i fetched API to my project, when i trying to use display on value, it doesn't work on the first click.我为我的项目获取了 API,当我尝试使用按值显示时,它在第一次点击时不起作用。 at the second click the function will run good and everything works.在第二次单击时,该功能将运行良好并且一切正常。 when im trying to log in the fetching function everything works good, but, at the display function i get an error: also if i write a number of pokemon to search and click to search it doesnt work but, if i change it and click again, i will get the first pokemon value.当我尝试登录获取功能时,一切正常,但是,在显示功能上我得到一个错误:如果我写了一些口袋妖怪来搜索并点击搜索它不起作用但是,如果我改变它并再次点击,我会得到第一个口袋妖怪值。

Uncaught TypeError: Cannot read properties of undefined (reading 'name')未捕获的类型错误:无法读取未定义的属性(读取“名称”)

im adding the function of the fetch and also the display function i can also send the git reposetory if anyone want to help.我添加了获取功能和显示功能,如果有人想提供帮助,我也可以发送 git 存储库。 thenks恩克斯

let fetetchPokemon = function (inputNum) {
      fetch(`${pokemonApi}` + `${inputNum}`)
        .then((response) => response.json())
    
        // .then((response) => console.log(response))
        .then(
          (response) =>
            (pokemon = new Pokemon(
              response.name,
              response.sprites,
              response.moves,
              response.types,
              response.abilities
            ))
        )
        // .then((pokemon) => console.log(pokemon.name));
        // .then((pokemon) => console.log(pokemon.name))
        .then(displayPokemon());
    };
    
    
    
    
    
    
    
    let displayPokemon = function () {
      pokemonName.innerText = pokemon.name;
      console.log(pokemon.name);
      pokemonImg.src = pokemon.image.front_default;
      displayMoves(pokemon.moves);
      displayType(pokemon.types);
      displayAbilities(pokemon.abilities);
    };

there is also a bin to see the code: https://jsbin.com/puvotid/edit?html,css,js,output还有一个bin看代码: https ://jsbin.com/puvotid/edit?html,css,js,output

use async and await to wait the results.使用asyncawait等待结果。

const fetchPokemon = async function(){
    await fetch(...).then(...)
}

The display method must be placed same scope with variable assignment.显示方法必须与变量分配放在相同的范围内。 So the method will look like所以方法看起来像

const fetetchPokemon = function (inputNum) {
  fetch(`${pokemonApi}` + `${inputNum}`)
    .then((response) => response.json())
    .then(
      (response) => {
        pokemon = new Pokemon(
          response.name,
          response.sprites,
          response.moves,
          response.types,
          response.abilities
        );
        
        displayPokemon();
      }
    );
};

As answer below from @Mamoud, you should use async/await or callback invidually, not both正如@Mamoud 下面的回答,您应该单独使用 async/await 或回调,而不是同时使用两者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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