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的值。
答案 0 :(得分:1)
每当调用函数
fn
时,它应该返回具有特定超时周期的a和b的值。
从上面的陈述我明白你需要在将来的某个时刻致电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}`);
});
答案 1 :(得分:0)
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);
}