问题
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