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
基础教程推荐
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
