You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现带超时机制的函数参数包装?基于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.

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 getProxy used a constructor-style approach with this, but we don't need an object here—we just need to return a wrapped function that handles the delay.
  • The original setTimeout called fn without passing any arguments, and it ran immediately once, not tied to calls to fn.

内容的提问来源于stack exchange,提问作者newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:53:51