我有一个照片上传处理程序的工作版本,但我想看看它如何与异步等待一起工作。下面是我使用 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/