简体   繁体   中英

How to pass a predefined javascript callback that returns a response, into a function as a parameter?

I need to call the same callback function multiple times, and so I don't want to have to repeat it, but it takes a response, and this response is somehow not available to the calling function unless I explicitly define it. Basically this is what I have:

// The callback function
function foo(response){
  //do something with the response here
}

// The calling function
mainActivity(data, function(response){
  // Upon receiving the data in the form of 'response', do foo to it 
  foo(response); 
});

What I would ideally like to do is:

mainActivity(data, foo(response)}

But I can't seem to figure out how.

Simple.

mainActivity(data, foo);

Though not if you're continuing to call foo() in mainActivity() .

Reasoning:

mainActivity(data, foo(response)) calls foo(response) and passes that to mainActivity(data, callback) . If foo(response) doesn't return a function, it's not going to be very successful when mainActivity tries to call it as a function (which would be callback(response) in the notional declaration).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM