/*
并发加载函数 防止接口重复提交以及查询
id:唯一值
syncFunc:Promise函数
*/
const _map={}
const _startTimeMap={}
function conCurentLoad (id,syncFunc) {
//兼容并发加载的情况
if(!_map[id]){
_map[id]=[];
_startTimeMap[id]=+new Date();
return syncFunc().then(function (res) {
setTimeout(function () {
if(_map[id].length>0){
_map[id].forEach(function (callback) {
callback(res)
})
}
delete _map[id]
},0)
return res;
})
}else{
const now=+new Date();
//10秒超时处理
if(now-_startTimeMap[id]<10000){
return new Promise(function (resolve) {
_map[id].push(resolve)
});
}else{
return syncFunc();
}
}
}
//demo
conCurentLoad(2,function () {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(22)
},100)
})
}).then(function (res) {
console.log(res)
})
conCurentLoad(2,function () {
return new Promise(function (resolve) {
setTimeout(resolve,100)
})
}).then(function (res) {
console.log(res)
})