Pass an Extra Argument to a Callback Function

Pass an extra argument to a callback function

Just create a function(magic) {} as a wrapper callback:

callWithMagic(function(magic) {
return processMagic(magic, 42);
});

Or using ECMAScript 6: arrow functions:

callWithMagic(magic => processMagic(magic, 42));

Passing extra argument to a return callback

You do not control the arguments to your callback. Those are set by the caller which is the internals of the doSomething() function which you say is not something you control. So, don't try to add things there that the caller isn't setting. That will only mess you up.

Instead, since you're using an inline callback, you can just directly access variables in the parent scope without defining them as arguments to the callback. This is a nice feature of Javascript (inline callbacks with access to parent scoped variables).

Here's a runnable example:

let arr = [1, 2, 3];

let inputParam = "something";

arr.forEach((item, i) => {

doSomething(inputParam, (err, result) => {

// you can access variables such as i in the parent scope here

// from an inline callback

//Use err and result

console.log("i: ", i);

});

});

function doSomething(param1, callback) {

// simulate async callback

setTimeout(function() {

callback(null, "hello");

}, 100);

}

Pass extra argument into callback

You can create an inline callback and call the event handler with any arguments you want.

Example:

client.on("foo", () => eventHandler.foo(client));

However, looking at your code, it appears that the on event is a property on the client itself. Can't you just edit the code of client and make it pass itself as an argument to the callback function?

JavaScript: How to pass extra parameters to a callback

You have two options here:

Either you swap the arguments, so that str comes first. Then you can use function.bind to bind the first arguments of the function:

function print(str, num) {
console.log(str + ": " + num);
}

array.forEach(print.bind(null, 'someStr'));

Alternatively, you can also create a new (anonymous) function which simply passes some value to the second argument:

array.forEach(function (item) { print(item, 'someStr'); });

With ES6 and the arrow functions, this even gets a bit prettier:

array.forEach(item => print(item, 'someStr'));

Both solutions have a very similar effect in that they create a new function object which is then passed to forEach. What makes more sense to you depends on your use cases.

And just as a note: You just need to remember that the callback passed to forEach actually takes up to three arguments (the item, the item’s index, and the array itself), so be careful when you pass a function that accepts other additional arguments. You can again use a local function to remedy that.

Passing arguments into a callback function

You're calling the function immediately, and passing its return value as the callback argument, not passing the function as a callback.

Use lambda to create a function that calls the function with an extra argument.

some_object.trace("w", lambda *args: cb(*args, var=some_var))

You can also use functools.partial to create a function with some arguments pre-specified.

from functools import partial

some_object.trace("w", partial(cb, var=some_var))

Passing extra arguments to callback function

You can use bind() to pre-define an extra argument to the callback function:

...
sub.on('message', onSubMessage.bind(sub, socket));
...

function onSubMessage(socket, channel, message) {
if (channel === 'chat') socket.send(message);
}

This does create a new function instance for every new connection, so there is probably not a real upside to using a wrapping function in terms of memory usage.

JavaScript: Passing parameters to a callback function

If you want something slightly more general, you can use the arguments variable like so:

function tryMe(param1, param2) {
alert(param1 + " and " + param2);
}

function callbackTester(callback) {
callback(arguments[1], arguments[2]);
}

callbackTester(tryMe, "hello", "goodbye");

Add extra parameters to callback function loop

Perhaps the best way is to actually pass the arguments for their respective function or just try to use a wrapper to calculate the time of a function.

Code taken from another question

from functools import wraps
from time import time

def timing(f):
@wraps(f)
def wrap(*args, **kw):
ts = time()
result = f(*args, **kw)
te = time()
print 'func:%r args:[%r, %r] took: %2.4f sec' % \
(f.__name__, args, kw, te-ts)
return result
return wrap

Then you can do something along the lines of

@timming
def dummy_function(self, period, letter='A'):
""" Debugging purposes only """
print(f'This function prints the letter {letter}.')
from time import sleep
sleep(3)


def calculate_insights():
dummy_function(era)

or you could just a dict with all the parameters passed into each callback but that doesn't sounds to pythonic for me.



Related Topics



Leave a reply



Submit