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

查看:86
本文介绍了使用异步/等待返回值获取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天全站免登陆