'Fetch API Using Async/Await Return Value Unexpected [duplicate]

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.



Solution 1:[1]

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

Solution 2:[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 => {})

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ele
Solution 2 Joseph
Solution 3 Dachi Natsvlishvili