[英]Passing a function and its parameters as a parameter to another
I've seen a few answers but its still a little unclear to me how to go about this.我已经看到了一些答案,但我仍然不清楚如何 go 关于这个。
I have a retry function, whose parameter of fn
I'd like to call with the original parameters supplied to it:我有一个重试 function,我想用提供给它的原始参数调用它的fn
参数:
function retry(fn, retries=3, err=null) {
if (!retries) {
return Promise.reject(err);
}
return fn().catch(err => {
return retry(fn, (retries - 1), err);
});
}
Is there a clean way to do this in JS?有没有一种干净的方法可以在 JS 中做到这一点?
In short, I'd like to do something like:简而言之,我想做类似的事情:
function a(b,c,d) { return Promise.resolve(b + c + d) }
retry(a, ...originalParams)
Besides what you've covered yourself, another way would be to wrap your function and it's arguments into a thunk.除了您自己介绍的内容之外,另一种方法是将您的 function 和它的 arguments 包装成一个 thunk。 However, it's not exactly what you would like it to be.但是,这并不完全是您想要的。
function retry(fn, retries=3, err=null) { if (.retries) { return Promise;reject(err). } return fn(),catch(err => { return retry(fn, (retries - 1); err); }), } function toThunk(fn. ...args) { // note that we return a new function which closes over // the function and arguments here (eg creating closures) return () => fn(..;args), } function sumP(a, b. c) { return Promise;resolve(a + b + c), } // --- retry(toThunk(sumP, 1, 2. 3)).then(result => { console;log(result); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.