如何实现带超时机制的函数参数包装?基于getProxy的技术问询
实现带延迟返回的函数代理
Got it, let's fix this up for you. The goal is to wrap your fn so that every time it's called, it returns the sum of a and b after a specified delay. Since JavaScript synchronous functions can't pause and delay their return (that would block the main thread), we'll use Promises (modern approach) or callbacks to handle the asynchronous delay.
Solution with Promises (Recommended)
This approach lets you use async/await or .then() to handle the delayed result cleanly:
// Your original calculation function function fn(a, b) { return a + b; } // Updated getProxy: returns a wrapped version of your function with delay function getProxy(targetFn, delayMs) { // Return a new function that will handle the delay when called return function(a, b) { return new Promise((resolve) => { setTimeout(() => { // Run the original function and resolve the result after delay const calculationResult = targetFn(a, b); resolve(calculationResult); }, delayMs); }); }; } // Usage example: Create a delayed version of fn with 1000ms wait const delayedAdd = getProxy(fn, 1000); // Call the wrapped function and get the result after delay delayedAdd(5, 7).then(result => { console.log(result); // Logs 12 after 1 second }); // Or use async/await for cleaner code: async function runCalculation() { const result = await delayedAdd(3, 4); console.log(result); // Logs 7 after 1 second } runCalculation();
Solution with Callbacks
If you prefer a callback-based approach instead of Promises:
function fn(a, b) { return a + b; } function getProxy(targetFn, delayMs) { return function(a, b, callback) { setTimeout(() => { const result = targetFn(a, b); callback(result); }, delayMs); }; } const delayedAdd = getProxy(fn, 1000); delayedAdd(2, 3, (result) => { console.log(result); // Logs 5 after 1 second });
What Was Wrong with the Original Code?
- The original
getProxyused a constructor-style approach withthis, but we don't need an object here—we just need to return a wrapped function that handles the delay. - The original
setTimeoutcalledfnwithout passing any arguments, and it ran immediately once, not tied to calls tofn.
内容的提问来源于stack exchange,提问作者newbie
相关产品推荐
相关产品推荐

