【问题标题】:Call async/await functions in parallel not working on React's componentDidMount并行调用 async/await 函数在 React 的 componentDidMount 上不起作用
【发布时间】:2018-05-21 21:42:08
【问题描述】:

我试图异步调用同一个 this.func 两次,this.func 发出一个 http 请求,但我可以通过网络选项卡看到这两个函数没有并行运行。我已经阅读了这些答案:answer 1, answer 2

    async componentDidMount() {     
   //...
    var applicationVersion2 = await Promise.all([this.func(this.state.applicationUrl), this.func(this.state.applicationUrl2)]); 
   //...
    }

现在怎么样了:

应该如何:

【问题讨论】:

  • 工人数量有限,这或许可以解释为什么不是所有 14 个调用都并行运行。
  • 这里不是很明显,但你确定this.func 是异步的和/或返回一个承诺吗?上图正是我对两个串联运行的非异步函数的期望。
  • 如果你展示这个可能会有所帮助。 func 可以。

标签: javascript reactjs asynchronous


【解决方案1】:

正如我在上面的 cmets 中提到的,我怀疑 this.func 不是异步代码和/或返回一个承诺,尽管没有看到它,很难确定。试试这个:

async componentDidMount() {     
  //...
  const first = this.func(this.state.applicationUrl)
  console.log(`First: ${first}`)   
  const second = this.func(this.state.applicationUrl2)
  console.log(`Second: ${second}`) 
  const applicationVersion2 = [await first, await second]
  //...
}

在您的 console.log 中,您应该看到:

First: Promise {<pending>}
Second: Promise {<pending>}

但我猜你会看到两者的非承诺值。如果是这种情况,请将 this.func 设为 async function 或从中返回 Promise

【讨论】:

  • 我试过了,它在控制台上看到了First: [object Promise],但在网络选项卡上它看起来和我的第一次打印一样。这是代码的print(一些函数和变量名称不同)。如果你不能重现我的问题,请告诉我,我会分享项目的完整代码
  • @Eduardo 实际上,如果您可以将这两个函数的代码(复制和粘贴)添加到您的原始帖子中,将会很有帮助。
  • 没关系。请参阅此处:gist.github.com/jayallen/746f122d70301502dcd0ad5bb46015cc 该代码肯定会同时加载资源。我不确定您的代码有什么问题。 :-/
  • 我在新项目上尝试了你的代码,它工作正常,我会搜索我的代码有什么问题,当我发现我会在这里发布,谢谢你的帮助
  • @Eduardo 我很高兴听到它并希望它有所帮助!
猜你喜欢
  • 2017-12-17
  • 2021-01-17
  • 2020-08-13
  • 1970-01-01
  • 2019-12-06
  • 2021-08-03
相关资源
最近更新 更多