我有一个可用的照片上传处理程序,但我想看看如何使用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)
})
}
我将它转换为async await,webpack没有显示任何错误,但是当我尝试在我的Web应用程序上测试时,发现当我执行console.log(this)
时,this
未定义。
下面是我的async await尝试:
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)
}
}
什么问题?
["transform-runtime", { "polyfill": false, "regenerator": true }]
- Sharon Chai