【问题标题】:Wait for all promises to resolve before updating state and redirect在更新状态和重定向之前等待所有承诺解决
【发布时间】:2021-06-27 08:19:53
【问题描述】:

我下面代码中的.then() 是在上传一张图片后触发的。那时更新我的​​状态变量并进行重定向还为时过早。在继续之前,我应该等待所有文件上传。有人可以为我指明实现这一目标的方向吗?

 const storageRef = app.storage()
 const [files, setFiles] = useState([])
 const [data, setData] = React.useState()

  const handleSubmit = () => {
    files.forEach((file) => {
      storageRef
        .ref(`${data.firebaseRef}/${file.id}`)
        .put(file)
        .then(() => {
          // Only if all files are uploaded to firebase then I need to do something
        })
    })
  }

提前致谢!

【问题讨论】:

    标签: reactjs firebase promise react-hooks firebase-storage


    【解决方案1】:

    使用Promise.all() 等待所有承诺解决后再做其他事情:

    const handleSubmit = () => {
      Promise.all(files.map(file =>
        storageRef
          .ref(`${data.firebaseRef}/${file.id}`)
          .put(file)
      )).then(() => {
        // Only if all files are uploaded to firebase then I need to do something
      })
    }
    

    【讨论】:

    • 嘿@Ori,这对我不起作用。 .then() 被立即调用
    • 我的结构有误,您的答案按预期工作。谢谢!
    猜你喜欢
    • 2014-03-12
    • 1970-01-01
    • 2020-08-28
    • 2018-12-14
    • 2022-01-17
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多