Reputation: 1510
I understand that callbacks are functions you pass as a parameter into another function, such as in the following simple example:
function operation(a,b, callback) {
return callback(a,b);
}
function add(a,b) {
return a+b;
}
function multiply(a,b) {
return a*b;
}
console.log(operation(5,4,add)); // 9
console.log(operation(5,4,multiply)); // 20
What confuses me greatly about callback functions is when they are used in chained function calls, such as the following:
// Angular example
$http.get(...).then(function(req,res) {
// some actions here
});
// JQuery example
$( "li" ).each(function( index ) {
// some actions here
});
In both examples, how are the parameters in the anonymous function populated? Does this in any way relate to the callback logic I gave in the operation function example I gave or is this some other concept entirely?
My best guess for the angular example is that the http promise returns an array object [req,res] and the function parameters are pulled from the array in sequential order.
What is of specific interest to me is how I could define my own chained function call in this style. How can I define something like:
myObject.performAction(function(param1, param2, param3) {
// do stuff
});
If someone could give an example like that, it would be amazingly instructive.
Upvotes: 0
Views: 196
Reputation: 1510
Based on Igor's answer, I came up with the following to mock the $http.get(...).then() syntax:
var myObject = {
transform: function (value) {
// Perform some logic based on the value parameter
var squared = value*value;
var cubic = value*value*value;
return {
a: squared,
b: cubic,
action: function(callback) {
callback(this.a, this.b);
}
}
}
};
myObject.transform(12).action(function(a,b) {
console.log(a+b); // 1872
});
The idea is that in the transform function, you perform some logic on the value parameter so that a
and b
are derived from some calculations instead of just being hardcoded values. That way the callback in action
becomes a lot more meaningful.
This effectively abstracts the parameters a
and b
from the user in the anonymous function call in action
. This is why these parameters have to be documented for the API call to myObject.transform.action
.
Upvotes: 0
Reputation: 15893
The parameters are passed to callback function by the calling code - same as in your example return callback(a,b);
var myObject = {
a: 1,
b: 2,
c: 3,
performAction: function(callback) {
callback(this.a, this.b, this.c);
}
};
myObject.performAction(function(param1, param2, param3) {
// do stuff
});
Upvotes: 3