使用Async/Await调用Fetch API返回值不符合预期问题咨询
getUserIP() Returns a Promise (and How to Fix It) Great question—this is a super common gotcha with async/await in JavaScript! Let’s break down why this happens and how to resolve it.
The Core Issue: Async Functions Always Return Promises
Any function marked with async will always return a Promise, no matter what. Even though you’re using await inside getUserIP() to wait for the fetch response, calling getUserIP() directly doesn’t pause your code to wait for the Promise to resolve. Instead, it immediately hands back a Promise object that will eventually hold your IP address once the fetch finishes. That’s why your console shows Promise { <state>: "fulfilled", <value>: "/* 我的IP地址 */" }—the Promise has resolved (hence "fulfilled"), but you’re looking at the Promise wrapper, not the actual value inside it.
The console.log(json.ip) inside your function works because that line runs after the await response.json() call, so it has access to the resolved value.
Solution 1: Use await When Calling getUserIP()
Since getUserIP() returns a Promise, you can use await to wait for it to resolve and get the actual IP. Just note: await can only be used inside an async function, or at the top level of your code (modern browsers and Node.js support top-level await now).
Example inside an async function:
async function getAndUseIP() { const ip = await getUserIP(); console.log(ip); // This will log your actual IP address! // Add any code that uses the IP variable here } getAndUseIP();
Top-level example (if allowed in your environment):
const ip = await getUserIP(); console.log(ip); // Actual IP address
Solution 2: Use .then() to Handle the Promise
If you can’t use await (e.g., older environments or non-async contexts), you can use the Promise’s .then() method to access the resolved value:
getUserIP().then(ip => { console.log(ip); // Actual IP here // Your code that uses the IP goes inside this callback });
Why the YouTube Example Worked
Chances are, the person in the YouTube video was using one of these two methods (either await when calling the function or .then()) but you might have missed that detail. It’s easy to overlook the await keyword when someone’s coding quickly!
内容的提问来源于stack exchange,提问作者Ibrahim

