Promise value issue on Javascript

I am having a problem in my code if anyone can help it would be great!

What I want:

To have a country variable that has a value of a country code, for example “PT” or “EN”.

I am using this API: “https://get.geojs.io/v1/ip/country.json”;

The code I’m using:

const ipInfo = async () => {
  let fetchVar = fetch(url);
  return fetchVar
    .then((res) => res.json())
    .then( async (out) => {
      let geoResultArr = out["country"];
      // console.log(geoResultArr);
      // langSportsCountry.push(geoResultArr);
      return geoResultArr;
    })
    .catch((err) => {
      throw err;
    });
};

let langSportsCountry = ipInfo();

The Problem

I can’t get the variable to only have the country code information “PT”. I am not sure if it is the way I am handling the promise or another problem that I am not understanding.

For example, this doesn’t work:

langSportsCountry.then(function(val) {
  let country = JSON.stringify (val);
  console.log(country);
  return country;
});

Hello @jon_snow , welcome to the forum.

What is exactly the issue you are experiencing?
What’s the output you are seeing?

You explained your desired outcome, but not the actual outcome.
Better details makes easier for people on the forum to help you. :slight_smile:

Thank you @Marmiz

The output at this time for the country variables is none, I’m unable to get the “PT” to be used on another function at this time.

If I instead use push to send the data to a new variable, I get an array and not a unique value that I can use.

It all depends on how you are actually trying to consume the promise.

As you just. pasted snippets it’s hard to give you a precise answer.

Anyway what I found peculiar is the fact that you are using async yet not using await and relying on then. How come? As async/await can greatly simplify how you wrote (and think) about the code execution.

For example:

async function getIp() {
  let response = await fetch()
  let json = await response.json()

  return json["country"]
}

To me looks more readable and easy to reason about

Hi!

Ok, I have simplified the code, but the issue that Im having is to get the value inside the country variable:

let url = "https://get.geojs.io/v1/ip/country.json";


      let langSportsCountry;

        const ipInfo = async () => {
          let response = await fetch(url)
          let json = await response.json()

          return json["country"]
        };
        
        langSportsCountry = ipInfo();

        // langSportsCountry.then((value) => console.log(value));

        let country = langSportsCountry.then((value) => (value));

        console.log(country);

fireStart;

const mainDataSports = async () => {

const sportsBooksPath = `sportsbooks_carrousel/`;

const dbRef = firebase.database().ref(sportsBooksPath);

return dbRef.child(country).get().then((snapshot) => {
  if (snapshot.exists()) {
    let infoSportsResult = snapshot.val();
    let infoSportsResultArr = Object.values(infoSportsResult);
    console.log(infoSportsResultArr);
    return infoSportsResultArr;
  } else {
    console.log("No data available");
    return null;
  }
}).catch((error) => {
  console.error(error);
});
}```

This line is not doing what you think it is doing. Async functions always return a Promise. So

langSportsCountry = ipInfo();

is setting langSportsCountry to a Promise, which you then have to handle to extract the country code that you returned from ipInfo(). You are using a then on langSportsCountry but it doesn’t return a value like you think it does and thus country is not being set the way you want it to (the console.log should show you what it is being set to). Inside of the then is where you would set the value of country (and also do the console.log to verify that it is set correctly). For example:

let country;
langSportsCountry.then((value) => {
      country = value;
      console.log(`country = ${country}`);
});

I’m not saying this is the answer to all your problems, I’m just demonstrating how to set the country variable to the country code returned by ipInfo() in the then() function.

Promises don’t guarantee when they will finish (the API server could be very slow at the moment and you may not get a response for several seconds), so any code that relies on the country code being set from the fetch will have to wait to be executed until you have successfully set whatever variable you intend to store it in. When you start adding Promises then it is up to you to ensure that everything runs in order.

Thanks!

Still not working, I get:

Reference.child failed: First argument was an invalid path = “undefined”. Paths must be non-empty strings and can’t contain “.”, “#”, “$”, “[”, or “]”

If I try to add this code inside my main function it won’t work.

I think I need to get this value to be available on a country global variable.

I have no idea what those errors are referring to. I would need to be able to run your code for myself to help troubleshoot this. Do you have this project in github or something where we can have access to the whole thing?

Regardless, make sure you really understand how Promises work. That should help you figure out what you need to do.

Thanks for your answer.

How would you make available the result on a global country variable?

I’m not sure I understand exactly what you are asking. A global variable is available anywhere, so you can assign it a value and reference it anywhere you like. But remember, when Promises are involved, it’s not just a matter of assigning a value to a variable. Any code that relies on that variable has to either wait until the variable has been assigned or has to handle the situation in which the variable hasn’t been assigned yet when the code is executed.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.