关于Promise.all优化问题

来源:5-6 JS 原型本章相关的面试题

又年00

2021-03-26

老师,关于下面一段代码重复太多,我想请教两个优化问题:
1、这里2个Promise.all数组里面的方法前两个都一样,因为这里面方法都是立即调用执行,怎么才能优化成通过判断条件修改数组里的执行函数,而不是写两个Promise.all。
2、then和catch里面的两行代码也是重复的,在当前业务就是有结果了就取消2个加载动画,这里可以优化成只写一次取消加载动画吗。

if (this.checkbox) {
     Promise.all([
         this.getSysRoleList(id),
         this.getDataRoleList(id),
         this.getCheckedSysRole(id)
     ])
         .then(res => {
             // 取消加载动画
             this.loading = false
             this.roleLoading = false
         })
         .catch(err => {
             this.loading = false
             this.roleLoading = false
         })
 } else {
     Promise.all([
         this.getSysRoleList(id),
         this.getDataRoleList(id)
     ])
         .then(res => {
             this.loading = false
             this.roleLoading = false
         })
         .catch(err => {
             this.loading = false
             this.roleLoading = false
         })
 }
写回答

2回答

慕的地5354100

2021-04-27

//每个子函数用Promise返回

var getSysRoleList = ()=>{

    return new Promise((resolve,reject)=>{

        resolve('getSysRoleList')

    })

}


var open = (checkbox)=>{

let arr = []

if (checkbox) {

arr = [

getSysRoleList(),

getDataRoleList(),

getCheckedSysRole()

]

}else{

arr = [

getSysRoleList(),

getDataRoleList(),

]

}

Promise.all(arr)

.then((res)=>{

console.log(res)

})

console.log(arr)

}


0
0

双越

2021-03-26

第一,优化就是用缓存。例如,写一个 async 函数,第一次用异步查询,并将结果缓存起来,接下来就可以直接使用缓存结果了。

第二,这个优化,根据目前的信息,我就帮不上忙了,因为我都不知道你为啥会有两个 loading 。想优化这个,得先把两个 loading 合并为一个,从 loading 功能上优化,然后这段代码自然就没有问题了。

0
0

一天时间高效准备前端技术一面 匹配大厂面试要求

针对时下面试高频考点,帮助新人js面试快速通关

4694 学习 · 1681 问题

查看课程