newbie
newbie

Reputation: 53

Wrapping a function's arguments by another function and calling it with some timeout period

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);

Above there is a function name getProxy which is used to wrap the values of it's arguments in such a way that whenever the function fn is called it should return the values of a and b with certain timeout period.

Upvotes: 0

Views: 152

Answers (2)

newbie
newbie

Reputation: 53

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);
}

Upvotes: 0

axiac
axiac

Reputation: 72256

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

From the statement above I understand you need to call fn at some moment in the future and get the value it returns.

If you don't care about the value returned by fn() then you don't even need the getProxy() function. All you have to do is to call:

setTimeout(fn, ms, a, b)

This call will postpone the execution of fn(a, b) with ms milliseconds. fn(a, b) will be executed asynchronously but the value it returns is lost.

You need to use a Promise to asynchronously run a function and capture the value it returns.

This is how your code should look like:

    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}`);
    });

Read about setTimeout() and Promise.

Upvotes: 1

Related Questions