You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何async componentDidMount中forceUpdate需等待funcLazyLoad的Promise完成?

问题:async componentDidMount中forceUpdate为何等待Promise解析?

我搞不懂,为什么在附带的代码示例里,async修饰的componentDidMount方法没有立刻执行forceUpdate,反而要等funcLazyLoad的Promise解析完成?我原本以为只有像await funcLazyLoad(1000).then(this.forceUpdate)这种写法,forceUpdate才会等待Promise解析。

import React from 'react'
import ReactDOM from 'react-dom'

let data = ''

async function funcLazyLoad(ms) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(ms)
    }, ms)
  })
}

class App extends React.Component {
  async componentDidMount() {
    data = await funcLazyLoad(1000)
    this.forceUpdate()
  }

  render() {
    console.log('Render')
    return <div>Hello {data}</div>
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

解答

这是因为await关键字的核心作用就是暂停当前async函数的执行流程,直到紧跟其后的Promise状态变为resolved。

在你的代码中:

  • data = await funcLazyLoad(1000)这一行执行时,funcLazyLoad会返回一个需要1秒才能resolve的Promise
  • await会让componentDidMount函数在这里“卡住”,直到1秒后Promise解析完成,把返回值赋值给data变量
  • 只有等这一步彻底完成,函数才会继续执行下一行的this.forceUpdate()

你提到的await funcLazyLoad(1000).then(this.forceUpdate)写法,本质和当前代码逻辑一致——都是等待Promise解析后再执行后续操作。区别只是:前者把后续操作写在await之后的同步代码块里,后者把操作放在Promise的then回调中。

总结来说,await就是专门用来让async函数内的代码等待Promise完成的,不管后续操作是直接写在await下一行,还是通过then绑定回调,都必须等Promise解析完毕才会触发。


内容的提问来源于stack exchange,提问作者diesel94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 02:12:34