使用debounce节流API请求时遇TypeError:函数未定义问题求助
问题分析与解决方案
错误核心原因
你写的debounce函数存在两个关键问题,导致了类型错误:
- 没有返回Promise:fetch本身是异步函数,返回Promise,但你的debounce返回的函数只是延迟执行fetch,没有把fetch的异步结果包装成Promise返回。当
getRelease返回throttleFetch(...)时,得到的是undefined(因为setTimeout是异步的,外层函数直接执行完毕,没有返回值),后续代码如果尝试对这个结果使用await或.then(),就会抛出类型错误。 - 未处理异步错误传递:即使延迟执行了fetch,也没有捕获其可能抛出的错误,无法传递给调用方。
而你之前的节流版本能正常运行,是因为createThrottler返回的是async函数,会自动将返回值包装成Promise,并且内部会await fetch的结果,最终返回的是fetch的Promise,完全符合调用方的预期。
修复后的debounce函数
修改后的函数会返回Promise,同时处理重复调用时的取消逻辑,传递异步结果和错误:
function debounce(func, timeout = 1000) { let timer; let cancelPrevious; return (...args) => { // 取消之前的延迟调用,并通知调用方请求已取消 if (timer) { clearTimeout(timer); cancelPrevious?.(new Error('Debounced request canceled')); } return new Promise((resolve, reject) => { cancelPrevious = reject; timer = setTimeout(async () => { try { // 执行原函数并等待异步结果 const result = await func.apply(this, args); resolve(result); } catch (err) { // 传递原函数抛出的错误 reject(err); } }, timeout); }); }; }
使用说明
修复后的throttleFetch调用后会返回Promise,和你之前的节流版本行为一致,getRelease可以正常返回这个Promise供后续代码处理:
const throttleFetch = debounce(fetch, 2500); function getRelease(idFiltered) { return throttleFetch(`https://api.example.com/your-endpoint?id=${idFiltered}`); } // 调用示例 getRelease(123) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));
内容的提问来源于stack exchange,提问作者double-happiness
相关产品推荐
相关产品推荐

