javascript - 使用 es2017 的异步等待重构 promise 和 promise.all

标签 javascript reactjs asynchronous ecmascript-6 async-await

我有一个照片上传处理程序的工作版本,但我想看看它如何与异步等待一起工作。下面是我使用 promise 的工作代码。

onChangePhotos = (e) => {
    e.preventDefault()

    let files = e.target.files

    if(files.length === 0) { return }

    const allow_photos_length = this.state.selectedAlbum.photos.length + files.length
    if(allow_photos_length > this.state.maxPhoto) {
      alert(`Maximum only ${maxPhoto} photos per album!`)
      return
    }

    this.setState({
      uploading_photo: true
    })

    let promises = []
    for(const file of files){
      promises.push(UploadApi.uploadPhoto('company', file))
    }

    Promise.all(promises)
    .then(responses => {

      let next_photos = []
      for(const [index, response] of responses.entries()) {
        const { upload_id, url } = response

        next_photos.push({photo_id: upload_id, url})

        if(responses.length === index + 1){
          this.setState({
            uploading_photo: false
          })
        }
      }

      this.setState({
        selectedAlbum: {
          ...this.state.selectedAlbum,
          photos: [
            ...this.state.selectedAlbum.photos,
            ...next_photos
          ]
        }
      })

    })
    .catch(err =>{
      this.setState({ uploading_photo: false })
      alert('failed to upload! Error: ' + err)
    })
  }

我将其转换为异步等待,webpack 没有显示任何错误,但是当我尝试在我的 webapp 上进行测试时,发现 this 在我执行 console.log(这个)

下面是我的异步等待尝试:

onChangePhotos = async (e) => {
    e.preventDefault()

    let files = e.target.files

    if(files.length === 0) { return }

    this.setState({
      uploading: true
    })

    let promises = []
    for(const file of files){
      const uploadPhotoPromise = await UploadApi.singlePhoto(file)
      promises.push(uploadPhotoPromise)
    }

    try {

      const responses = await Promise.all(promises)

      let next_photos = []
      for(const [index, response] of responses.entries()) {
        const { upload_id, url } = response

        next_photos.push({photo_id: upload_id, url})

        if(responses.length === index + 1){
          this.setState({
            uploading: false
          })
        }
      }

      this.setState({
        selectedAlbum: {
          ...this.state.selectedAlbum,
          photos: [
            ...this.state.selectedAlbum.photos,
            ...next_photos
          ]
        }
      })

    } catch(err) {
      this.setState({ uploading: false })
      alert('failed to upload! Error: ' + err)
    }
  }

有什么问题?

最佳答案

不确定错误是什么意思,因为缺少信息,但是你的 promises 数组没有 promises,因为你已经使用了 await:

我建议改变这个:

let promises = []
for(const file of files){
  const uploadPhotoPromise = await UploadApi.singlePhoto(file)
  promises.push(uploadPhotoPromise)
}

到:

const promises = [];

for(const file of files){
  promises.push(UploadApi.singlePhoto(file))
}

关于javascript - 使用 es2017 的异步等待重构 promise 和 promise.all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49272045/

相关文章:

javascript - 如何在 async.eachSeries 回调函数中调用回调函数

javascript - 仅调用数组中的最后一个对象,async.each 或eachSeries 不起作用

javascript - 替换本地字符并将其与变量进行比较

javascript - React - 如何手动触发子组件的鼠标输入

javascript - PeerJS - connection.on ('open' )未执行

javascript - 使用 AngularJS/NodeJS 将 PEM 证书添加到 Http 请求

javascript - 异常管理器.js :84 Unhandled JS Exception: ReferenceError: response is not defined

javascript - 为什么我的 React enzyme 快照测试在 document.getElementById() 调用上失败?

javascript - typescript 源解析 : get interface related to certain react class

javascript - 异步函数是否总是需要使用await 来调用?