解決方案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 = {};
複製代碼