0

I was trying to get the client IP address using ipify API. I have used fetch and await & I am getting the right response by calling the prototype. But while I am trying to return the value from the function and trying to store it on a const variable, it's showing undefined. I need the IP address value to pass on weather API. code:-

class CurrentLocaion{
     //Fetch current IP from api ipfy
    async getCurrentIpAddress(){
        const response = await fetch('http://api.ipify.org/?format=json');

        const responseData = await response.json();
        return responseData;
    } 
}
//init currentlocation object
const currentLocation = new CurrentLocaion();

function getIpAddress(){
    currentLocation.getCurrentIpAddress()
    .then(results =>{
        return results.ip;
    })
}

const ipvalue = getIpAddress();
console.log(ipvalue);

I think I might have done some silly mistake, But unable to discover. Any help will be a big thank you.

isuro
  • 96
  • 10
  • 3
    You can't turn async code into sync code. You need to `await`, `then` or callback to get the value. `getIpAddress` has to return the promise chain and the caller needs to `then` or `await` on it. Or pass a callback into `getIpAddress`. – ggorlen Jan 09 '21 at 07:38
  • 1
    Welcome to the wonderful world of asynchronism! – Jeremy Thille Jan 09 '21 at 07:50
  • `const ipvalue = (await currentLocation.getCurrentIpAddress()).ip` – Jeremy Thille Jan 09 '21 at 07:51

0 Answers0