我有一个照片上传处理程序的工作版本,但我想看看如何使用async await。以下是我使用promise的工作代码。
<div class="row">
<div class="col-xs-4 col-sm-4 padding-0">
<img src="/images/chatti.png" alt="5" >
</div>
<div class="col-xs-4 col-sm-4 padding-0">
<img src="/images/sofa.png" alt="5" >
</div>
<div class="col-xs-4 col-sm-4 padding-0">
<img src="/images/slider.png" alt="5" >
</div>
</div>
我将其转换为异步等待,webpack没有显示任何错误,但是当我尝试在我的webapp上进行测试时,发现我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)
})
}
时没有定义this
。
以下是我的异步等待尝试:
console.log(this)
有什么问题?
答案 0 :(得分:2)
由于缺乏信息,不确定错误是什么意思,但你的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))
}