【问题标题】:promise is still pending in then block - how to resolve? [duplicate]承诺仍在 then 块中待处理 - 如何解决? [复制]
【发布时间】:2019-06-16 02:16:20
【问题描述】:

我有类似的代码 -

fetch(`${URL}${PATH}`)
   .then(res => {
       const d = res.json();
       console.log("data is: ", d);

       return d;
    })

它记录data is: Promise { <pending> }。

如何查看结果并在下一个代码语句中使用?

其他问题和答案建议使用 then 块来解决,但我仍然看到它未解决。

【问题讨论】:

  • res.json() 也是异步的。请参阅此处的第一个示例:MDN: Using Fetch。
  • 这建议then解决,但我的即使在那个块中也是未决的。
  • 你读过 Tylers 的评论吗?你需要处理res.json()中的承诺aswell
  • @Prakhar fetch 需要 两个 thens。 fetch() -> then -> result.json() -> then -> process result.
  • 好吧 - 我是这个世界的新手。我现在明白了。

标签: javascript typescript fetch isomorphic-javascript isomorphic-fetch-api


【解决方案1】:

res.json() 是异步的。您将需要使用额外的 .then 来获得结果。

fetch(`${URL}${PATH}`)
  .then(res => res.json())
  .then(d => {
    console.log('data is: ', d);
    return d;
  });

【讨论】:

  • 这与graphql-request - return request(this.GRAPHQL_ENDPOINT, query, variables) .then(res => { console.log('data is: ', res); return res; }) 的工作方式是否不同
  • 显然我现在正在等待处理?
【解决方案2】:

如果你得到这种类型的值 Promise { <pending> }。永远记得解决它。
所以您的查询将解析为

fetch(`${URL}${PATH}`)
   .then(res => res.json())
   .then(console.log)
   .catch(console.error)

为了更好地理解,您可以利用 async/await 功能。上面的代码会减少到-

try{
   const res = await fetch(`${URL}${PATH}`)
   const dataAsJson = await res.json()
   console.log(data)
}
catch(ex) {
   console.error(ex)
}

【讨论】:

  • 如何在调试器中解决?
猜你喜欢
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2021-03-27
  • 2020-04-21
  • 2016-12-13
  • 2022-01-20
  • 2020-02-05
  • 2020-08-14
相关资源
最近更新 更多