【问题标题】:Fetch returns promise when I expect an array当我期望一个数组时,Fetch 返回承诺
【发布时间】:2019-05-16 15:35:27
【问题描述】:

我正在做一个简单的 api 获取请求,但我似乎无法自行隔离数组。它总是在一个承诺中,我不确定如何删除它或如何访问存储在数组中的值。

function getLocation(name) {

  let output = fetch(`http://dataservice.accuweather.com/locations/v1/cities/search?apikey=oqAor7Al7Fkcj7AudulUkk5WGoySmEu7&q=london`).then(data => data.json());
  return output

}

function App() {

  var output = getLocation(`london`);
  console.log (output)
...
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(3)

是 console.log 中显示的内容 我只需要 Array(3)

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

fetchPromise#then总是返回一个承诺。要访问它获取的信息,请使用 Promise:

getLocation()
.then(data => {
    // use the data
})
.catch(error => {
    // Handle/report the error
});

或在异步函数中:

const data = await getLocation();

旁注:您的getLocation 有一个非常 常见错误(我在我贫血的小博客上wrote it up 很常见):它不检查HTTP 操作是否成功。 fetch 仅在 network 错误时失败,而不是 HTTP 错误。修复它:

function getLocation(name) {
    return fetch(`http://dataservice.accuweather.com/locations/v1/cities/search?apikey=oqAor7Al7Fkcj7AudulUkk5WGoySmEu7&q=london`)
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error, status = " + response.status);
        }
        return response.json();
    });
}

【讨论】:

  • @TJCrowder 这导致了另一个问题,我如何将 .then(data => ... 设置为可以在函数外部使用的变量。
  • @blujay - 嗨!你不是唯一一个有这个问题的人,人们经常问这个问题。 :-) 查看this question 的答案。答案here 也可能有用。编码愉快!
  • @Daniel - 谢谢!!令人惊讶的是,我注意到我在输入时错过了它,但后来又忘记了回去修复它。
  • @TJCrowder 谢谢,我仍然掌握 => 的窍门哈哈
  • @blujay - 不用担心!只是FWIW,它与箭头功能无关,它可能是一个传统功能,你会遇到同样的情况。
猜你喜欢
  • 2021-01-28
  • 2019-05-05
  • 2020-06-26
  • 2021-04-11
  • 2015-11-27
  • 2017-05-09
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多