Marmiton
Marmiton

Reputation: 161

JavaScript - Why does my API call variable return undefined?

i am developing a simple application for checking highscores, currently i have the API returning it's value to the console, however when i try to interact with this data it's returning undefined

In the below code I am calling the API with 'await highscores.getStats' but for example when i attemtp to console.log the value of 'highScoreData' it returns undefined. I'm very new at JS programming so any help would be appriciated.

currently the api returns a json object and prints it's value to the console. this is all working correctly.

const Hiscores = require('osrs-hiscores').default;
const hiscores = new Hiscores({
  timeout: 6000
});


async function getHighscores() {
  let namePara = document.getElementById("UsrName").value;
  let typePara;
  let validArgument = false;

  if (namePara.length <= 12 && namePara.length > 0) {
    console.log("Valid Name");
    validArgument = true;
  } else {
    console.log("Invalid Name");
    validArgument = false;
  }
  if (validArgument === true) {

    console.log(`Player Name: ${namePara}`);
    const highScoreData = await hiscores.getStats(`${namePara}`)
      .then(res => console.log(res))
      .catch(err => console.error(err));

  }
}

Upvotes: 0

Views: 883

Answers (1)

eloyra
eloyra

Reputation: 529

When you use the await syntax you shouldn't use then/catch, the result is in the "highScoreData" constant, that's what you should log. Also, if you want to catch errors using the await syntax, you should use the try/catch approach more familiar to those coming from other programming languages like Java or PHP.

try {
  const highScoreData = await hiscores.getStats(`${namePara}`);
  console.log(highScoreData);
} catch (err) {
  console.error(err);
}

Upvotes: 2

Related Questions