将更多参数传递给回调函数

时间:2018-03-16 20:11:10

标签: javascript express

假设我有一个方法发出POST,然后调用适当的回调函数来处理响应:

myService.verify(id, verificationCallback);

function verificationCallback(err, response) { ... }

也许这个问题是双重的。似乎有2个隐式参数传递给verificationCallback(这是这种情况吗?这是如何工作的?)

那么我如何能够将第三个参数传递给该回调?我会做点什么:

myService.verify(id, verificationCallback(err, response, someOtherArgument));

这会因为当前上下文中没有errresponse变量而中断吗?我会使用arguments对象访问这些变量吗?

可能的解决方案(?)

Using an anonymous function:

myService.verify(id, function(err, response) {
    // Access my other variable here
    someOtherArgument === ...
});

由于

3 个答案:

答案 0 :(得分:1)

myService.verify(id, verificationCallback(err, response, someOtherArgument));

这不起作用。它会立即调用具有(很可能)未定义变量的函数。

参数不是隐式传递的,而是在验证函数内调用函数时显式传递的。见JonasW的anwer。

这是一个可能的解决方案:

function callback(yourThirdArgument) {
    return function(err, response) {
       ...
    }
}

用法:

myService.verify(id, callback(someOtherArgument));

答案 1 :(得分:1)

您可以使用.bind()。将null附加到this值,someOtherArgument将作为回调的第一个参数传递。这是一个MDN链接,可获取更多信息。

const someOtherArgument = "";

// Use .bind() to attach an argument to your callback.
myService.verify(id, verificationCallback.bind(null, someOtherArgument));

function verificationCallback(someOtherArgument, err, response) { ... }

答案 2 :(得分:0)

我不会称之为隐式

  const myService = {
   verify(id, cb){
    //...
    cb(null, "data"); // <----
   }
 };
相关问题