我尝试使用Promise.all上传完成多张图片后采取一些措施。
但是,then
之后的代码在调度代码之前运行。
我在这里有什么困惑?
submit_all_images({ dispatch, rootState }) {
const imageFileArray = rootState.imageStore.imageFileArray
var promiseArray = []
for ( var imageFile of imageFileArray ) {
promiseArray.push(dispatch('get_signed_request', imageFile))
}
Promise.all(promiseArray)
.then(results => {
console.log("finished with results: " + results)
return dispatch('submit_entire_form')
});
},
get_signed_request ({ dispatch, commit, state }, imgFile) {
const requestObject = {imageName: imgFile.name, imageType: `${imgFile.type}`}
axios.post('http://localhost:3000/sign-s3', requestObject)
.then(response => {
if (response.body.signedRequest && response.body.awsImageUrl) {
const signedRequest = response.body.signedRequest
const awsImageUrl = response.body.awsImageUrl
dispatch('upload_file', { imgFile, signedRequest, awsImageUrl })
} else {
alert('Could not get signed URL.');
}
}, error => {
console.log("ERROR: " + error)
})
},
upload_file ({ dispatch, commit, state}, { imgFile, signedRequest, awsImageUrl }) {
axios.put(signedRequest, imgFile, {
headers: {'Content-Type': imgFile.type}
}).then(response => {
console.log('finished uploading file: ' + imgFile.name )
commit(types.UPDATE_LICENSE_IMG_URLS, awsImageUrl)
}, error => {
alert("fail")
console.log(error)
})
},
答案 0 :(得分:1)
我不完全确定,因为我没有使用过vuex的经验,但我猜您错过了一些return
语句。
get_signed_request({ dispatch, commit, state }, imgFile){
const requestObject = {imageName: imgFile.name, imageType: `${imgFile.type}`}
//here
return axios.post('http://localhost:3000/sign-s3', requestObject)
.then(response => {
if (response.body.signedRequest && response.body.awsImageUrl) {
const signedRequest = response.body.signedRequest
const awsImageUrl = response.body.awsImageUrl
//here
return dispatch('upload_file', { imgFile, signedRequest, awsImageUrl })
} else {
alert('Could not get signed URL.');
}
}, error => {
console.log("ERROR: " + error)
})
},
upload_file({ dispatch, commit, state}, { imgFile, signedRequest, awsImageUrl }){
//here
return axios.put(signedRequest, imgFile, {
headers: {'Content-Type': imgFile.type}
}).then(response => {
console.log('finished uploading file: ' + imgFile.name )
//and here
return commit(types.UPDATE_LICENSE_IMG_URLS, awsImageUrl)
}, error => {
alert("fail")
console.log(error)
})
},
以便get_signed_request
返回仅在axios.post().then()
完成后才能解析的承诺,这取决于首先解析dispatch('upload_file', ...)
upload_file
同样取决于根据axios.put().then()
解析commit(types.UPDATE_LICENSE_IMG_URLS, awsImageUrl)