This is how callback functions work…
If this is confusing, don’t let it discourage you. Once you take a minute to add a callback to one of your own functions, it should become clearer. To create one, just add the callback as a parameter to your function signature, then from inside your function, invoke the callback. Of course, you can name it whatever you want, just make sure you invoke it with an open and close parenthesis and pass in whatever arguments are necessary to make it useful.
Let’s write a function with a callback.
Now we can create a couple objects and use this function with whatever callback we want, be it anonymous or not. Here’s what it looks like with an anonymous function.
In most cases, I prefer to declare callbacks separately. It keeps things a little cleaner. Note that you will need to define the correct parameters in the signature of your callback function. Then just pass a reference to the callback as the second argument (in this case). Also note that we’re passing a reference, and NOT invoking the callback. Don’t confuse the parenthesis that surround the parameters in the anonymous version with the parenthesis that invoke. It’s the job of the parent function to invoke the callback.
Just to be clear, although the
greet function uses the exact same variable names as the
fetchPerson function, that is not a requirement. If we want to use the arguments passed to our callbacks, then we need to have those variables in our function signature, but they could be named anything. Obviously, you always want to use meaningful variable names, but it could also be written as such…
…and that would still work—but don’t do that.
So there you have it. Go forth and prosper.