3
votes

Here's the function:

const getUserIP = async () => {
  let response = await fetch('https://jsonip.com/');
  let json = await response.json();

  console.log(json.ip)
  return json.ip;
};

In the console, the IP address is logged as expected. However, when I save the 'IP address' to a variable:

const ip = getUserIP();

And then type ip in the console, the value is shown as:

Promise { <state>: "fulfilled", <value>: "/* my IP here*/" }

I've watched videos on YouTube who have used the same logic/syntax albeit for a different API, but it works. I've searched Google and SO and couldn't find a thread with the same issue.

What am I missing?

Thanks.

3
Lots of duplicates of this question. I marked one of them. This is a common misunderstanding of how async/await works. Worth reading some doc/articles on them.jfriend00

3 Answers

5
votes

Async functions return Promises, you need to get that value as follow:

getUserIP().then(ip => console.log(ip)).catch(err => console.log(err));

Or, you can add the async declaration to the main function who calls the function getUserIP:

async function main() {
    const ip = await getUserIP();
}
2
votes

async functions return a Promise, and its resolved value is whatever you return from it. To get ip, you must use then.

getUserIP().then(ip => {})
1
votes

You have to add .then to getUserIP() because async function is returning a promise.

getUserIp().then(ip => console.log(ip));

You can also

(async() => {
    const ip = await getUserIP();
    console.log(ip);
})();