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/