使用异步/等待返回值意外获取 API

2022-01-20 00:00:00 fetch javascript promise

函数如下:

const getUserIP = async () => {
  let response = await fetch('https://jsonip.com/');
  let json = await response.json();

  console.log(json.ip)
  return json.ip;
};

在控制台中,IP 地址按预期记录.但是,当我将IP 地址"保存到变量时:

In the console, the IP address is logged as expected. However, when I save the 'IP address' to a variable:

const ip = getUserIP();

然后在控制台输入ip,值显示为:

And then type ip in the console, the value is shown as:

Promise { <state>: "fulfilled", <value>: "/* my IP here*/" }

我在 YouTube 上观看过使用相同逻辑/语法的视频,尽管 API 不同,但它确实有效.我已经搜索了 Google 和 SO,但找不到具有相同问题的线程.

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.

我错过了什么?

谢谢.

推荐答案

异步函数返回 Promises,你需要按如下方式获取该值:

Async functions return Promises, you need to get that value as follow:

getUserIP().then(ip => console.log(ip)).catch(err => console.log(err));

或者,您可以将async声明添加到调用函数getUserIP的主函数中:

Or, you can add the async declaration to the main function who calls the function getUserIP:

async function main() {
    const ip = await getUserIP();
}

相关文章