【问题标题】:How to get the JSON from promise [duplicate]如何从承诺中获取 JSON [重复]
【发布时间】:2019-01-20 09:09:15
【问题描述】:

代码:

fetch(`https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=++++++++++&tags=obama&format=json&extras=url_m&nojsoncallback=true`, {
    method: "GET",
    headers : { 
      'Content-Type': 'application/json',
      'Accept': 'application/json'
     }
  }).then(response => {
    console.log(response.json())
  })

输出:

Promise {_40: 0, _65: 0, _55: null, _72: null}

【问题讨论】:

  • 然后再添加一个:fetch(...).then(resp => resp.json()).then(data => ...)
  • 为什么要在GET 请求中发送Content-type 标头?您不会使用GET 发送任何内容。

标签: javascript json react-native


【解决方案1】:

然后添加另一个:

fetch(...).then(resp => resp.json()).then(data => ...)

请注意,fetch 只会在网络错误时出错,如果您希望它拒绝 Promise,例如500 响应,您必须检查状态代码并抛出:

fetch(url)
  .then(resp => {
     // you'll need to supply the function that checks the status here
     if (http_response_ok(resp.status)) {
       return resp.json();
     } else {
       throw new Error(`Got back ${resp.status}`);
     }
  }).then(data => {
     // happy path
  }).catch(err => {
     // sad path
  });

【讨论】:

  • 获取自:可能未处理的 Promise Rejection (id: 0):
  • @SalmanGhumsani 添加一个 catch 处理程序,请参阅我的更新答案。
  • 得到:console.log("sad path")
  • 查看 stackoverflow.com/questions/38842499/… 了解有关 react-native 警告的信息
  • @SalmanGhumsani do console.log(err); 你应该会看到实际的错误。
【解决方案2】:

您可以等待回复:

fetch(url, options).then(async (response) => {
  const data = await response.json();
  console.log(data)
})

【讨论】:

  • 是的,很酷,这就是工作,我看起来一样,谢谢:)
猜你喜欢
  • 1970-01-01
  • 2022-12-17
  • 2020-12-17
  • 2018-05-16
  • 2021-05-23
  • 2017-10-18
  • 2021-04-18
  • 2017-02-07
相关资源
最近更新 更多