[英]pass a callback function with some arguments already set
I am trying to preload arguments into a callback function. 我正在尝试将参数预加载到回调函数中。 Here's a stripped down example of what I'm attempting.
这是我正在尝试的简化示例。
function doSomething(callback) {
// code to obtain a 3rd argument, eg API call or access a file.
// let's say we are getting the number 5.
const c = 5;
// invoke the callback with its final argument.
callback(c);
}
function toBeCalled(arg1, arg2, arg3) {
// do a calculation with these arguments.
console.log((arg1 * arg3) + arg2);
}
// invoke doSomething with the first two arguments already defined.
// eg user input.
doSomething(toBeCalled(a, b));
what I want to happen: 我想发生的事情:
doSomething(toBeCalled(4, 2));
console: 22
I've given the callback its first two arguments when I invoke doSomething. 在调用doSomething时,我已经给回调函数提供了前两个参数。 doSomething grabs the value of the third argument from somewhere and invokes the callback with the 3rd value added.
doSomething从某处获取第三个参数的值,并调用添加了第3个值的回调。
what actually happens: 实际发生的情况:
As far as I'm aware the code above would invoke toBeCalled too early which is causing the error: 据我所知,上面的代码会太早调用toBeCalled,这会导致错误:
TypeError: callback is not a function
Thank you for any help! 感谢您的任何帮助!
Just wrap it in another function: 只需将其包装在另一个函数中:
f = function (c) {
toBeCalled(4, 2, c)
}
Then pass f
as the callback to receive the final argument: 然后传递
f
作为回调以接收最终参数:
doSomething(f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.