Promise 同步处理异步进程。
2018-09-11 本文已影响13人
TouchMe丶
uploadQiniu(imgSource){
return new Promise((resolve,reject)=>{
const uptoken = this.props.uiStore.imgupload.token;
const file = imgSource;
const key = null;
let config = {
useCdnDomain: false,
region: null,
uphost:".........."
};
let putExtra = {
fname: imgSource.name,
params: {},
mimeType: ["image/png", "image/jpeg","image/jpg"]
};
let observable = qiniu.upload(file, key, uptoken, putExtra, config);
observable.subscribe({
next:(res)=>{
},
error: (err) => {
_mutil.errorTips(err);
},
complete: (res) => {
resolve(this.props.uiStore.imgupload.domain + res.hash);
}
})
});
}
handleFiles(e){
let imgList = e.target.files;
let fileMaxSize = 5000000;
//promise all 定义的参数数组
let promiseArr = [];
for(let i=0;i<imgList.length;i++){
if(!/image\/\w+/.test(imgList[i].type)){
_mutil.errorTips("必须上传图片文件!");
return false;
}
if(imgList[i].size <= fileMaxSize){
promiseArr[i] = this.uploadQiniu(imgList[i]);
}else{
_mutil.errorTips(imgList[i].name + "不合要求或文件过大!");
return false;
}
}
Promise.all(promiseArr).then(result =>{
let newList = this.state.uploadList.concat(result);
if(newList.length >= 10){
_mutil.warningTips("图片最多只能上传10张,自动为您保存10张图!");
newList.length = 10;
}
this.setState({
uploadList:newList //[...this.state.uploadList,...result]无返回值
});
})
}