用es2017的异步等待来重构promise和promise.All [英] refactor promise and promise.all with async await of es2017

查看:96
本文介绍了用es2017的异步等待来重构promise和promise.All的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a working version of a photo upload handler but I would want to see how it work with async await. Before anything below is my working code using 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上进行测试时,发现在执行console.log(this)时未定义this.

I convert it to async await, webpack did not show any error, but when I try to test on my webapp, found that this is not defined when I do console.log(this).

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

Below is my async await attempt:

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:

Not sure what the error is suppose to mean, because of lack of information, but your promises array has no promises, because you already use 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))
}

这篇关于用es2017的异步等待来重构promise和promise.All的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆