首先Promise.all() 中要传入的是一个数组, .all 会等待这个数组中的每一项都完成后,才会进入到 .then 中,如果其中有一项出错了,就会进入到.catch中
代码:
Promise.all(
that.companyIntegralPolicyList.map((i)=>{
if(i.isEdit===1){ // 表明该数据处于编辑状态
var form = {
remark:i.remark,// 说明
tagScore: i.tagScore,//积分
id:i.id,
creditCode:i.creditCode
}
console.log(form,'12123')
return $httpRequest({
url: '/app/warehouse/company/integral/policy/save',
param: {param: form},
})
}
})
)
.then(function (res) {
let form = layForm ? layForm : layui.form
that.form = layForm.val("upholdForm");
that.form.creditCode = that.info.creditCode
that.form.companyName = that.info.name
// 如果三个必填项中 任意一个有值的话,就触发,提交的操作
if(that.form.dimensionTypeCode!==''||that.form.dimensionTypeItemCode!==''||that.form.tagScore!==''){
if(checkForm(that.form, that.rules)) {
$httpRequest({
url: '/app/warehouse/company/integral/policy/save',
param: {param: that.form}
}).then(function (res) {
if(res.resultCode == 200) {
setTimeout(function () {
layForm.render()
})
$showSuccess('操作成功')
setTimeout(()=>{$closeDialog(that.itIndex)},1000)
}
})
}
}else{
$showSuccess('操作成功')
setTimeout(()=>{
$closeDialog(that.itIndex)
},1000)
}
})
上面代码的意思:遍历数组,返回每项中的请求,待所有的请求都结束后,会进入到 .then中,执行下面的操作。
案例二:同一个方法,中有多个axios请求,但是要等到所有请求都完成后,才进行success的提示
原代码:
const sendOk = () => {
if (state.sendForm.ownerIdList.length > 0) {
ownerResend({
ownerIdList: state.sendForm.ownerIdList
}).then((res) => {
message.success('Success')
})
}
if (state.sendForm.isSms || state.sendForm.isEmail) {
sendMesage({
id: state.currentApplication.id,
isSms: state.sendForm.isSms,
isEmail: state.sendForm.isEmail
}).then((res) => {
message.success('Success')
})
}
state.visible.send = false
}
修改后:
const sendOk = async () => {
try {
const promises = [];
if (state.sendForm.ownerIdList.length > 0) {
const ownerResendPromise = ownerResend({
ownerIdList: state.sendForm.ownerIdList
});
promises.push(ownerResendPromise);
}
if (state.sendForm.isSms || state.sendForm.isEmail) {
const sendMessagePromise = sendMesage({
id: state.currentApplication.id,
isSms: state.sendForm.isSms,
isEmail: state.sendForm.isEmail
});
promises.push(sendMessagePromise);
}
if (promises&&promises.length) {
state.visible.send = false;
await Promise.all(promises);
message.success('success');
} else{
state.visible.send = false;
}
} catch (error) {
console.log(error);
}
// if (state.sendForm.ownerIdList.length > 0) {
// ownerResend({
// ownerIdList: state.sendForm.ownerIdList
// }).then((res) => {
// message.success('Success')
// })
// }
// if (state.sendForm.isSms || state.sendForm.isEmail) {
// sendMesage({
// id: state.currentApplication.id,
// isSms: state.sendForm.isSms,
// isEmail: state.sendForm.isEmail
// }).then((res) => {
// message.success('Success')
// })
// }
// state.visible.send = false
}