简体   繁体   English

将 function 及其参数作为参数传递给另一个

[英]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.

相关问题 使用参数传递函数作为JavaScript中另一个函数的参数 - Passing function with parameters as parameter of another function in JavaScript 将带有参数的函数作为另一个函数的参数传递 - Passing a function with parameters as parameter of another function 传递带有参数的function作为参数? - Passing a function with parameters as a parameter? 将 function 参数作为参数传递并将参数传递给该 function? - Passing a function parameter as parameter and passing parameters to that function? 将函数传递到另一个函数(带有参数) - Passing function into another function (with parameters) 将一个函数传递给另一个函数的参数 - Passing a Function into a Parameter of Another Function 如何从传递 2 个参数的函数中仅返回 1 个参数,并且能够在另一个函数(JavaScript)中访问它 - How can I return just 1 parameter from a function that is passing 2 parameters in it, and be able to access it in another function (JavaScript) 将参数从函数传递到其回调 - Passing parameters from function to its callback 在 JavaScript 中将带有查询参数的 URL 作为函数参数传递 - Passing URL with query parameters as function parameter in JavaScript 将带有参数的函数作为参数传递给jQuery的回调 - Passing function with parameters as a parameter to a jQuery's callback
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM