我有一个接口,传入id,传出value;
由于多处需要使用到这个接口,我就想到可以把这些id拼接后,进行请求再进行分发;
const set = new Set();
let timer;
function collect(idList) {
return new Promise((resolve, reject) => {
idList.forEach((id) => {
set.add(id);
});
clearTimeout(timer);
timer = setTimeout(async () => {
const valueList = await getValue();
resolve(
valueList
.filter((item) => idList.includes(item.id))
.map((item) => item.value)
);
}, 300);
});
}
// 模拟请求
function getValue() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(Array.from(set).map((id) => ({ id, value: id + '' })));
}, 300);
});
}
collect([1, 2, 3, 4]).then((list) => {
console.log(list);
});
collect([1, 3, 5, 7]).then((list) => {
console.log(list);
});
collect([9, 8, 7, 6]).then((list) => {
console.log(list);
});
// 期望输出
// ['1', '2', '3', '4']
// ['1', '3', '5', '7']
// ['9', '8', '7', '6']
// 实际输出
// ['9', '8', '7', '6']
我是这么写的,但是这样的话 resolve
就被 clearTimeout
清除了。
这种情况下,应该怎么处理?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…