Skip to content Skip to sidebar Skip to footer

Fetch Api Using Async/await Return Value Unexpected

Here's the function: const getUserIP = async () => { let response = await fetch('https://jsonip.com/'); let json = await response.json(); console.log(json.ip) return js

Solution 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:

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:

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

Post a Comment for "Fetch Api Using Async/await Return Value Unexpected"