3

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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Ibrahim
  • 332
  • 3
  • 14
  • 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 Apr 04 '18 at 23:30

3 Answers3

5

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();
}
Ele
  • 33,468
  • 7
  • 37
  • 75
2

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 => {})
Joseph
  • 117,725
  • 30
  • 181
  • 234
1

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);
})();