javascript - 用另一个函数包装一个函数的参数并在一定的超时时间内调用它

标签 javascript

function getProxy(fn, ms, a, b)
{
    this.a=a;
    this.b=b;
    this.ms=ms;    
    this.fn=fn;
    fn();
}

function fn(a, b)
{
    return a+b;
}   
var ms=setTimeout(fn, 1000);

上面有一个名为 getProxy 的函数,它用于包装其参数的值,这样每当调用函数 fn 时,它都应该在一定的超时时间内返回 a 和 b 的值。

最佳答案

whenever the function fn is called it should return the values of a and b with certain timeout period.

从上面的语句中我知道您需要在将来的某个时刻调用 fn 并获取它返回的值。

如果您不关心 fn() 返回的值,那么您甚至不需要 getProxy() 函数。您所要做的就是调用:

setTimeout(fn, ms, a, b)

此调用会将 fn(a, b) 的执行推迟 ms 毫秒。 fn(a, b) 将异步执行,但返回的值会丢失。

您需要使用 Promise异步运行函数并捕获它返回的值。

您的代码应如下所示:

    function getProxy(fn, ms, a, b) {
        // Create and return a new Promise
        return new Promise(function(resolve, reject) {
            // Start the async operation
            setTimeout(function() {
                // After the timeout, call fn(a, b) and resolve (fulfill)
                // the promise with the value returned by it
                resolve(fn(a, b));
            }, ms);
        });
    }

    // The promised computation
    function fn(a, b)
    {
        return a+b;
    }

    // Start processing
    let x = 2, y = 3;
    console.log(`Delaying the computation of ${x}+${y}...`)

    // Create the promise; it will run asynchronously
    let proxy = getProxy(fn, 1000, x, y);
    // Set event handlers for its completion
    proxy.then(function(result) {
        // ... 1000 ms later
        console.log(`Computation completed successfully: ${x}+${y}=${result}`);
    }).catch(function(error) {
        // handle the rejected promise (it won't be rejected in this example)
        console.log(`Computation failed. Reason: ${error}`);
    });

了解setTimeout()Promise .

关于javascript - 用另一个函数包装一个函数的参数并在一定的超时时间内调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49913753/

相关文章:

javascript - 带有外部图像的 box2d-js 元素

javascript - 我想在选择单选按钮时显示表格

javascript - 分隔值列表的正则表达式,其中值可能包含分隔符

javascript - d3 为数组中的每个对象创建路径,而不是使用每个对象的 x 和 y 属性

javascript - 以编程方式选择操作表会引发错误

javascript - {{csrf_token}} 给我 403 Forbidden 和 {%csrf_token%} 给我 500 服务器错误

javascript - 防止 iPad 上的 Safari 窗口弹跳并允许选择 Scrubber

javascript - 创建嵌套对象数组 Javascript

javascript - 如何在 Controller 中使用 ocLazyLoad 依赖注入(inject)?

javascript - 标记视频不适用于 onmouseover 和 onvideoout