使用异步/等待返回值意外获取 API [英] Fetch API Using Async/Await Return Value Unexpected

查看:15
本文介绍了使用异步/等待返回值意外获取 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数如下:

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

这篇关于使用异步/等待返回值意外获取 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆