Fetch API Using Async/Await Return Value Unexpected(使用异步/等待返回值意外获取 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用异步/等待返回值意外获取 API


基础教程推荐
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01