场景:同一个页面多次调取同一个接口,只是传参不一样。以下模拟:获取用户列表,每次传参多个用户ids
思路:
- 每次调用封装的api2后,都要返回promise,而resolve是后台返回后执行。此时需要把所传参数和resolve都保存到一个list中,等待后面遍历执行。
- 一定时间内,把所有参数合并,只向后台发送一次请求
- 后台返回数据后,通过id筛选对应的promise,并resolve返回
代码:
function getTwoJson(params){
return fetch('./1.json').then(res=>{
return res.json()
})
}
function fetchData(apiFun){
let requestObj = [];
return function(...args){
let params = args[0];
let timeout = args[1];
return new Promise((resolve,reject)=>{
requestObj.push({params,resolve:resolve})
requestObj.timer && clearTimeout(requestObj.timer)
requestObj.timer = setTimeout(()=>{
let allParams = getAllParams(requestObj);
apiFun(allParams).then(res=>{
console.log(allParams);
requestObj.map(linkRequest=>{
let data = res.filter(d=>linkRequest.params.includes(d.id))
linkRequest.resolve(data);
})
requestObj = [];
})
},timeout)
})
}
}
function getAllParams(obj){
let arr = [];
obj.forEach(d=>{
arr.push(...d.params)
})
let set = new Set(arr);
return [...set];
}
let getData = fetchData(getTwoJson)
getData([1,2],2000).then(res=>{
console.log(res);
}).catch(err=>{
})
getData([1,2,3],2000).then(res=>{
console.log(res);
}).catch(err=>{
})
getData([3,4],2000).then(res=>{
console.log(res);
}).catch(err=>{
})
setTimeout(()=>{
getData([3,4],2000).then(res=>{
console.log(res);
}).catch(err=>{
})
},4000)
欢迎大家批评指正