前段时间在用uniapp做项目时,多个图片同时进行压缩上传时,uni.compressImage()这里是一个异步处理,还没等图片全部压缩完成,就已经开始后台上传文件操作了,但是uni.compressImage()这个方法本身没有异步转同步的属性,这时候就用Promise对象解决了异步转同步的问题。
//图片上传
let uploadImgLength = this.imgList.length;
if (uploadImgLength > 0) {
//压缩图片需要使用Promise异步转同步处理
let promise = new Promise(function(resolve, reject) {
_this.imgList.map((value, index) => {
uni.compressImage({
src: value.path,
quality: 20,
success: (res) => {
_this.compressedImgList.push(res.tempFilePath);
if (index == uploadImgLength - 1) {
resolve(_this.compressedImgList);
}
},
fail: (err) => {
reject(err)
}
})
})
})
promise.then(res => {
console.log(res);
let imgs = res.map((value, index) => { //picA picB picC 命名方式
switch (index) {
case 0:
index = "A";
break;
case 1:
index = "B";
break;
case 2:
index = "C";
break;
}
return {
name: 'pic' + index,
uri: value
}
})
uni.request({
url: _this.GLOBAL.serverSrc + 'tree/treeExist',
method: 'POST',
data: {
stree_no: data.stree_no
},
success: res => {
if (res.data == 0) {
uni.showLoading({
title: '苗木录入中'
})
uni.uploadFile({
url: _this.GLOBAL.serverSrc + 'upload/uploadTreeImage?userid=' + this.userInfo.id + '&gardenId=' +
data.garden_id,
files: imgs,
fileType: 'image',
success: (res) => {
console.log(res);
let result = JSON.parse(res.data);
if (result.result == 1) {
data.picname = result.data;
data.token = JSON.stringify(uni.getStorageSync('uerInfo'));
//添加数据
uni.request({
url: this.GLOBAL.serverSrc + 'tree/addTree',
method: 'POST',
data: data,
header: {
"content-type": "application/x-www-form-urlencoded"
},
success: res => {
if (res) {
uni.hideLoading();
uni.showToast({
title: '录入成功',
duration: 2000
})
}
}
});
}
}
})
} else {
uni.showToast({
title: '苗木编号已存在',
icon: 'none',
duration: 2000
})
}
}
})
})
}
在这个就明白了就很容易理解Promise 是怎么做的异步转同步,以上代码中可以看到resolve 和 reject 俩个参数
resolve()是将Promise的状态由未完成变为成功
reject()是将Promise的状态由未完成变为失败
我们只有将Promise 的状态置为成功,才会进行下一步动作
let promise = new Promise(function(resolve, reject) {
_this.imgList.map((value, index) => {
uni.compressImage({
src: value.path,
quality: 20,
success: (res) => {
_this.compressedImgList.push(res.tempFilePath);
if (index == uploadImgLength - 1) {
resolve(_this.compressedImgList);
}
},
fail: (err) => {
reject(err)
}
})
})
})
那么上面就是用一个if语句判断我什么时候才将Promise置为成功,并在resolve(_this.compressedImgList);专递下一步动作需要用到的变量,这个时候就可以用Promise.then()来接受变量并执行下一步操作
promise.then(res => {
console.log(res);
})
这个时候console.log打印出来的res正是_this.compressedImgList传递的内容。