我有一个照片上传处理程序的工作版本,但我想看看它如何与异步等待一起工作。在下面的内容之前是我使用 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 wait,webpack 没有显示任何错误,但是当我尝试在我的 webapp 上测试时,发现this
当我这样做时没有定义console.log(this)
.
以下是我的异步等待尝试:
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)
}
}
有什么问题?
由于缺乏信息,不确定错误的含义是什么,但是您的 Promise 数组没有 Promise,因为您已经使用了await
:
我建议改变这个:
let promises = []
for(const file of files){
const uploadPhotoPromise = await UploadApi.singlePhoto(file)
promises.push(uploadPhotoPromise)
}
to:
const promises = [];
for(const file of files){
promises.push(UploadApi.singlePhoto(file))
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)