What is callback?
callBack :
An event handler is a particular type of callback,
A callback is a just function, that passed into another function,with the expatiation that the call Back will call at the particular time.
We just saw , callBacks are used to be the main way asynchronous functions were implemented in java-script.
callBack based functions are hard to call the function,that accept a function.This is common situation if you need to perform some operations that breaksdown into a series of asynchronous functions.
function obj(init, callback) {
const result = init + 1;
callback(result);
}
function obj1(init, callback) {
const result = init + 2;
callback(result);
}
function obj2(init, callback) {
const result = init + 3;
callback(result);
}
function object() {
obj(0, (result1) => {
obj1(result1, (result2) => {
obj2(result2, (result3) => {
console.log(result3);
});
});
});
}
object();
The code defines three functions (obj
, obj1
, obj2
) that take an initial value and a callback function.
The
object
function is defined, which chains these functions together, passing their results to each other in sequence.When
object
is called, it initiates a nested series of function calls, starting withobj
, thenobj1
, and finallyobj2
.Each function adds a different number (
1
,2
, or3
) to the initial value and passes the result to the next function in the chain.The final result of
init + 1 + 2 + 3
is logged to the console.Thus, the output is
6
, showing the cumulative result of adding1
,2
, and3
to the initial value of0
.