【问题标题】:How do I retrieve fetch PromiseValue in async?如何异步检索 fetch PromiseValue?
【发布时间】:2020-09-08 11:03:23
【问题描述】:

我正在尝试以这样的异步方式获取获取的结果:

var result = await fetch(`/api/collection/get-collection.php?name=${this._name}`, {method: `GET`});
console.log(result.json());

但是当我查看控制台时,我得到了这个:

Promise {<pending>}
  __proto__: Promise
  [[PromiseStatus]]: "resolved"
  [[PromiseValue]]: Object
    content: (176) [...]
    extra: {...}
    message: ...
    __proto__: Object

所以我觉得当涉及到 console.log 时,promise 仍然是未决的? (有一个工具提示说“刚刚评估了下面的值”,所以我猜它会在承诺解决时更新?当然下面的代码(此处未显示)不起作用,因为它需要 fetch 的返回值。我甚至不知道如何访问 PromiseValue。

进行异步获取调用的正确方法是什么?

PS:我使用的是香草 JS。

【问题讨论】:

  • result.json() 返回另一个 Promise,您需要将其发送到 await
  • 请注意:永远不要让 Promise 不被接受(不好的做法)。
  • 哦。好的,就是这样,你能写一个答案让我验证它吗?附带说明一下,如果您对如何编写适当的异步调用有建议(如果有的话,我的意思是好的做法)。
  • @Kai Lehmann 好吧,如果你有一个代码示例来说明如何编写一个好的异步调用,那我真的很陌生(承诺和异步等等)。我正在尝试阅读有关该主题的内容,但其中大部分内容都超出了我的想象。
  • 简单地说,async/await 只是让基于 promise 的代码看起来同步的语法糖。

标签: javascript asynchronous promise


【解决方案1】:

您可以像这样使用 async-await 进行 fetch 调用。

try {

   const response = await fetch(`/api/collection/get-collection.php?name=${this._name}`, {method: `GET`});

   const result = await response.json()

   // do something with the data
   console.log(data);

} catch(error) {

  // your error handling code

  console.log(error)

}

如果您不想使用 async-await,那么您可以使用 .then 来解决 promise。

 fetch(`/api/collection/get-collection.php?name=${this._name}`, {method: `GET`})
        .then(res => res.json())
        .then(data => {
           // do something with the data
           console.log(data)
         })
        .catch(error => {
            // your error handling code
            console.log(error)
         });

【讨论】:

    猜你喜欢
    • 2018-05-01
    • 2020-12-03
    • 2014-12-02
    • 1970-01-01
    • 2019-12-16
    • 2019-05-29
    • 1970-01-01
    • 2020-11-10
    • 2015-07-02
    相关资源
    最近更新 更多