javascript - 即使链接了“.then”,Promise 也“未决”,问题仅在使用正常功能时发生
问题描述
我目前正在尝试使用 API 来获取访问者的 IP 地址。使用以下代码时,我收到“承诺未决”消息:
function getIPAdd(){
var ip = fetch('https://pro.ip-api.com/json/?key=KEY').then(response => response.json()).then(data => data);
return ip;
}
var ipAdd = getIPAdd();
console.log(ipAdd);
我得到这个输出:
Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
这意味着承诺正在履行,但由于某种原因,仍未完成?
如果我使用以下代码:
(function(){
fetch('https://pro.ip-api.com/json/?key=KEY').then(response => response.json()).then(data => console.log(data));
})();
我没有收到任何“未决的承诺”问题。我猜这是因为它是由于console.log
后一个代码示例中使用的方式,但是我怎样才能修复第一个代码示例,以便我以我需要的方式获得我的 JSON 输出。
解决方案
您需要解决fetch
返回的承诺。像这样的东西应该工作:
function getIPAdd(){
var ip = fetch('https://pro.ip-api.com/json/?key=KEY').then(response => response.json());
return ip;
}
var ipAdd = getIPAdd();
ipAdd.then(data => console.log(data));
另一种方法是使用await
关键字。唯一的问题是你只能从一个async
函数中这样做。所以这里有一个例子:
const getIP = () => fetch('https://pro.ip-api.com/json/?key=KEY').then(response => response.json())
const main = async () => {
ip = await getIP();
console.log(ip)
}
main();
推荐阅读
- python - 从 lightkurve 导入 search_targetpixelfile 会导致分段错误/内核崩溃
- javascript - 具有多种收音机和文本输入类型的 Javascript 测验
- c# - 如何在 C# 中实现关于方法的简短描述?
- c# - 尝试查看数据时出现数据库错误
- java - 传输和保存 MultipartFile 实例
- javascript - 呈现页面时未定义对象数组。页面重新呈现时的潜在混乱
- python - 如何使用 Python 从 JSON 模式生成 JSON 样本?
- typescript - 基于输入返回任何对象键类型或对象类型本身的通用 Typescript 方法
- python - 当我尝试通过 pip 安装 mysqlclient 时,只允许在 C99 模式下遇到“for”循环初始声明错误
- javascript - Vue.js 相同的值被传递到方法中