Could someone help me understand how this is working?
I understand how callbacks work but I was watching a tutorial video and came across this snippet of code:
function addAndHandle(n1, n2, cb) {
const result = n1 n2;
cb(result);
}
addAndHandle(10, 20, function (results) {
console.log(results);
});
My question in this is, how is results
being calculated here in the callback. In the function declaration, the result
is being passed into the callback which makes sense because the sum is being stored in result
. However, later I am using results
so how is that showing the sum of 10
and 20
or whatever n1
and n2
are?
CodePudding user response:
You call the function with the three parameters.
The function adds n1 and n2 and saves the result in a variable
Then you pass that Varbiable to the function.
Maybe naming the parameter different helps
function addAndHandle(n1, n2, cb) {
const result = n1 n2;
cb(result);
}
addAndHandle(10, 20, function (p_nResult) {
console.log(p_nResult);
});
CodePudding user response:
Maybe writing it like this will help you understand:
function addAndHandle(n1, n2, cb) {
const result = n1 n2;
cb(result);
}
function foo(results) {
console.log(results);
}
addAndHandle(10, 20,foo);
Inside addAndHanle function you call cb - you are calling foo, result is equal to 30. It's the same as calling foo with 30:
foo(30)
So - results is calculated with const result = n1 n2
, this gives you a value that you pass on to foo.
In your example you are using anonymous function as callabck, but the logic is the same. All i did was to extract your cb into a separate function to simplify it.
CodePudding user response:
I think you are confused since result
and results
are the same in this example. Your result
is passed into your callback
(function (results) {console.log(results);}
) as results
These are the values your working with at the end
function addAndHandle(n1 /* 10 */, n2 /* 20 */, cb /* function (results) {console.log(results);} */) {
const result = n1 n2; /* 30 */
// This is just calling your callback function from below with the value of result eg. 30
cb(result /* 30 */);
// in case your familiar with IIF
(function (results) {console.log(results);})(result)
addAndHandle(10, 20, function (results /* 30 */) {
console.log(results /* 30 */);
});