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

て烟熏妆下的殇ゞ 提交于 2020-01-04 04:24:10

问题


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.


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



回答2:


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



回答3:


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 => {})


来源:https://stackoverflow.com/questions/49661185/fetch-api-using-async-await-return-value-unexpected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!