需求
为了减少页面等待时间,现有多个接口,需要同时调用。
解决
有两种写法:
Promise.all([interfaceName1(para1), interfaceName2(para2)]).then().catch()
Promise.all(arr)
中的参数 arr :由接口名称(接口参数)组成的数组;
then((res) => {})
中的结果 res:接口结果所组成的数组。
例1
loadClsOps() {
let promiseValues = [
// 获取该项目所有的标准列表
stanSelectOps({
projectId: this.projectId,
}),
// 获取项目类数据
getProClsByStan({
projectId: this.projectId,
}),
];
Promise.all(promiseValues)
.then((res) => {
this.libList = res[0].data.map((e) => ({
id: e.id,
treeId: "stan+" + e.id,
name: e.libraryName,
type: 1,
isStan: true,
}));
let proClsObj = res[1].data;
// 拼接树选项:构造节点唯一标识 treeId
this.clsOps = this.libList.map((item) => {
let obj = { ...item };
const { id, treeId } = item;
const target = Object.keys(proClsObj).find((key) => key == id);
if (target) {
obj.children = this.prefixId(proClsObj[target], `${treeId}+`);
}
return obj;
});
console.log("clsOps:", this.clsOps, "libList:", this.libList);
})
.catch((err) => console.log({ err }));
},
例2
submitForm() {
const basicForm = this.$refs.basicInfo.$refs.basicInfoForm;
const genForm = this.$refs.genInfo.$refs.genInfoForm;
Promise.all([basicForm, genForm].map(this.getFormPromise)).then((res) => {
const validateResult = res.every((item) => !!item);
if (validateResult) {
const genTable = Object.assign({}, basicForm.model, genForm.model);
genTable.columns = this.columns;
genTable.params = {
treeCode: genTable.treeCode,
treeName: genTable.treeName,
treeParentCode: genTable.treeParentCode,
parentMenuId: genTable.parentMenuId,
};
updateGenTable(genTable).then((res) => {
this.$modal.msgSuccess(res.msg);
if (res.code === 200) {
this.close();
}
});
} else {
this.$modal.msgError("表单校验未通过,请重新检查提交内容");
}
});
},
getFormPromise(form) {
return new Promise((resolve) => {
form.validate((res) => {
resolve(res);
});
});
},
asycn 和 await 结合 try{}catch(err){}
例子
async getAfterDetail () {
try {
const res = await getAfterDetail(this.$route.query.id)
this.detail = res.data
const res2 = await getDetailById(this.detail.saleOrderId)
this.orderDetail = res2.data
} catch (error) {
console.log(error)
}
},