使用背景:
多张图片调用图片上传接口时,先上传的图片接口返回顺序可能在后面。
解决方法:
使用Promise异步执行
1. 图片预上传回调方法–先压缩图片质量再调用上传服务器接口
afterRead(files) {
const _this = this
if (files.file) {
new Compressor(files.file, {
quality: 0.6,
success(result) {
const newFile = result
let formData = new FormData()
formData.append('file', newFile, newFile.name)
request(
{
method: 'post',
url: 'http://**',
data: formData
})
.then((response) => {
const obj = {}
obj.url=response.result
_this.form.photos.push(obj)
})
.catch(function (error) {
console.log(error)
})
}
})
} else {
let PromiseArr = files.map((item, index) => {
return this.handleUpload(item, index)
})
Promise.all(PromiseArr).then(value => {
_this.form.photos = _this.form.photos.concat(value)
})
}
},
2. 定义多张图片上传Promise
handleUpload(item, index) {
return new Promise(((resolve, reject) => {
new Compressor(item.file, {
quality: 0.6,
success(result) {
const formData = new FormData();
formData.append('file', result, result.name);
request(
{
method: 'post',
url: 'http://**',
data: formData
})
.then((response) => {
let str = response.result
resolve(str)
})
.catch(function (error) {
console.log(error)
})
}
})
}))
},