首页 > 解决方案 > 即使链接了“.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 输出。

标签: javascriptpromisefetch

解决方案


您需要解决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();

推荐阅读