解决方案javascript
const list = {};
debounce(fun) {
return new Promise((resolve, reject) => {
let d = Date.now();
list[d] = [resolve, reject];
//console.log(list);
if (!list["time"]) {
list["time"] = true;
let type = null, data = [];
fun.then(d => {
type = 0;
data = d;
})
.catch(e => {
type=1
})
.finally(d => {
for (let i in list) {
if (Array.isArray(list[i])) {
list[i][type](data);
}
}
list = {};
})
}
})
}
复制代码
效果是只调用一次,返回多个结果java
this.debounce(server.serverSearchNews({
"page": {
"maxResultCount": 20,
"pageNo": 1,
"pageSize": 5,
"skipCount": 0
}
}));
this.debounce(server.serverSearchNews({
"page": {
"maxResultCount": 20,
"pageNo": 1,
"pageSize": 5,
"skipCount": 0
}
}))
this.debounce(server.serverSearchNews({
"page": {
"maxResultCount": 20,
"pageNo": 1,
"pageSize": 5,
"skipCount": 0
}
}));
this.debounce(server.serverSearchNews({
"page": {
"maxResultCount": 20,
"pageNo": 1,
"pageSize": 5,
"skipCount": 0
}
}));
复制代码
若是将 //console.log(list); 打开则显示正常,可是若是将其注释则只成功1个或两个,没有找到具体缘由,由于初步怀疑是时间戳作key因运行速度快几乎同时,key重复形成的,因此改动代码,在时间戳部分加入 let d = Date.now() + (LIST["time"] || 0); 增长访问惰性,解决问题,可是具体形成缘由,有两个怀疑点。函数
debounce(fun) {
return new Promise((resolve, reject) => {
let d = Date.now() + (LIST["time"] || 0);
LIST[d] = [resolve, reject];
LIST["time"] && clearTimeout(LIST["time"]);
LIST["time"] = setTimeout(() => {
let type = null,
data = [];
fun.then(d => {
type = 0;
data = d;
})
.catch(e => {
type = 1
})
.finally(d=>{
console.log(LIST);
for (let i in LIST) {
if (Array.isArray(LIST[i])) {
LIST[i][type](data);
}
}
LIST = {};
})
})
})
}
let LIST = {};
复制代码