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的值。
发布于 2018-04-23 05:48:46
function getProxy() {
    //arguments;
    var context = this;
    var args = Array.prototype.slice.call(arguments);
    var fn = args[0], ms = args[1];
    setTimeout(function () {
        console.log(args, context);
        console.log(fn.apply(context, args.slice(2)));
    }, ms);
}发布于 2018-04-20 06:20:39
每当函数
fn被调用时,它都应该返回具有特定超时时间的a和b的值。
从上面的声明中,我了解到您需要在将来的某个时候调用fn并获得它返回的值。
如果您不关心fn()返回的值,那么甚至不需要getProxy()函数。你所要做的就是打电话:
setTimeout(fn, ms, a, b)此调用将以fn(a, b)毫秒的时间推迟fn(a, b)的执行。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的文章。
https://stackoverflow.com/questions/49913753
复制相似问题