项目需求是,后台只提供字典单个查询接口,而页面中需要用到的字典较多,后续接口又需要等待全部字典请求完成,因此只使用await需要逐次请求字典接口13次,效率极低。
因此结合promise.all(),对接口请求逻辑进行改造,以下是改造前代码:
data部分:
dictArr: [
{
key: 'sglx' // 事故类型
},
{
key: 'fxdj' // 风险等级
},
{
key: 'xcpc' // 巡查频次
},
{
key: 'fxkzlb' // 风险控制类别
},
{
key: 'gkcj' // 管控层级
},
{
key: 'fxys' // 风险因素
},
{
key: 'wxyspzt' // 危险源审批状态
},
{
key: 'gfx_in_or_open' // 高风险作业内部/公开
},
{
key: 'gfx_irradiate_type' // 高风险作业照射类型
},
{
key: 'gfx_gfxzyfj' // 高风险作业分级
},
{
key: 'gfx_status' // 高风险作业创建的流程状态
},
{
key: 'gfx_zyzt' // 高风险作业完成情况的流程状态
},
{
key: 'gfx_sfwc' // 高风险作业完成情况是否完成
}
],
method部分:
// 查询所有字典
async getAllDicts() {
// 拿到字典类型统一查字典
for (const dicItem of this.dictArr) {
try {
const { data } = await _getByTypeKeyForComBo(dicItem)
this.hazardsDict[dicItem.key] = data
} catch (error) {
console.log(error)
this.hazardsDict[dicItem.key] = []
}
}
},
调用部分:
async created() {
this.loading = true
await this.getAllDicts() // 数据字典接口(HazardsDictMixins)
// await this.getUserList() // 用户数据接口(HazardsDictMixins)
await this.getAllSites() // 场所数据接口(HazardsDictMixins)
await this.getAllOrg() // 查询组织数据接口下拉树
this.typeList1 = await this.handleQueryRiskTypeList() // 查询高风险作业分类(第一层级)
this.getList()
},
以下是改造后代码:
method部分:
async getAllDicts() {
// 拿到字典类型统一查字典
try {
const arr = []
// 生成多个函数
for (const dicItem of this.dictArr) {
arr.push(_getByTypeKeyForComBo(dicItem))
}
// 并发执行,并等待最慢的执行完成
Promise.all(arr).then((res) => {
let i = 0
for (const dicItem of this.dictArr) {
this.hazardsDict[dicItem.key] = res[i].data
i++
}
})
} catch (error) {
console.log(error)
}
},
代码改造以后,页面初次加载效率提升了2倍以上。