直接上代码
const test1 = () => {
console.log('test1');
return 1;
}
const test2 = _.debounce(test1, 100);
test2();// undefined 这里如何获取到 1 ??
// console->test1
直接上代码
const test1 = () => {
console.log('test1');
return 1;
}
const test2 = _.debounce(test1, 100);
test2();// undefined 这里如何获取到 1 ??
// console->test1
按照你说的返回一个promise
function debounceP(fn, delay=300) {
let timer = null;
return function debounce(...args) {
return new Promise((resolve, reject) => {
clearTimeout(timer);
timer = setTimeout(() => {
try { resolve(fn.apply(this, args))}
catch(e) {reject(e)}
}, delay);
})
}
}
function test() {
console.log('test')
return Date.now();
}
var p = debounceP(test)
p().then(console.log) // 防抖剔除
p().then(console.log) // 防抖剔除
p().then(console.log) // 输出
setTimeout(() => p().then(console.log), 300) // 在防抖延时的300ms之后调用,故输出
已参与了 SegmentFault 思否「问答」打卡,欢迎正在阅读的你也加入
13 回答13k 阅读
7 回答2.2k 阅读
3 回答1.4k 阅读✓ 已解决
6 回答1.3k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
6 回答1.2k 阅读
debounce后的test是异步调用的你无法获取到他的返回值,不过你可以传一个回调函数获取值