【问题标题】:Using a promise with Fetch API response still has my data returning as undefined使用带有 Fetch API 响应的 Promise 仍然让我的数据返回未定义
【发布时间】:2020-11-06 08:38:25
【问题描述】:

我正在构建一个简单的网络应用程序,允许用户在视频游戏中搜索玩家的统计数据。

这是我的代码

let player = [];
let proxy = "https://cors-anywhere.herokuapp.com/"
    let url =  proxy + "https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=Hess"

function getPlayer() {
  return fetch(url)
    .then((response) => response.text())
    .then((data) => console.log(data));
}
getPlayer().then((playerData) => {
  console.log(playerData);
  playerData.push(player);
  console.log(player);
});

如您所见,我正在尝试 console.log 响应并将响应推送到数组 player,以便稍后我可以使用 player 数组中的受感染数据来执行一些其他操作。

为什么它返回未定义?为什么我的回复不会被推送到player 数组中?

【问题讨论】:

  • 您想使用player.push(playerData),并且您还想删除控制台登录getPlayer().then(),或者在getPlayer()返回的最后一个.then()中进行回调data(所以它在下一个返回的承诺中可用)。请记住,player 中的数据只有在您推送到它后才可用,这是异步发生的。

标签: javascript arrays asynchronous promise fetch


【解决方案1】:

let player = [];
let proxy = "https://cors-anywhere.herokuapp.com/"
let url = proxy + "https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=Hess"

function getPlayer() {
    return fetch(url)
        .then((response) => response.text())
        .then((data) => {
            console.log(data)
            return data;
        });
}
getPlayer().then((playerData) => {
    console.log(playerData);
    player.push(playerData);
    console.log(player);
});

您需要确保在 .then() 的每一步都返回一个值。而你的 .push 是错误的方式

【讨论】:

  • 嗯,好吧,我明白了,所以基本上我是正确的,除了我需要使用“return”这一事实。不过我其实是通过这个链接theprogrammershangout.com/resources/javascript/promises/…了解到这个解决方案的,可以看到,这个例子并没有使用return。事实上,我之前使用过 fetch 并且正在做类似的事情,并且从不需要返回。如果使用 Promise 的全部目的是“等待”,那么为什么需要 return 感到困惑
  • 写 .then((data) => { return data } 和写 .then((data) => data) 是一样的。这可能是造成混乱的原因
【解决方案2】:

正如我所见,您可能在这里错误地切换了数组和数据 在下面的代码中,您不小心将数组推送到 playerData 而不是 opisite

playerData.push(player);

你应该这样做 player.push(playerData)

我认为你也应该删除第二个然后如果你按照人们所说的控制台记录它来获取数据但我认为你也可以使用第一个然后如果你想要第二个就这样做:

    function getPlayer() {
  return fetch(url)
    .then((response) => response.text())
    .then((data) => data);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    相关资源
    最近更新 更多