-
Notifications
You must be signed in to change notification settings - Fork 0
25 Call Back
Biswajit Sundara edited this page Aug 18, 2023
·
1 revision
A callback function is a function passed into another function as an argument
- which is then executed or called back at a later point in time
- The primary purpose of a callback function is to allow asynchronous or event-driven programming
- where certain code needs to be executed after the completion of a specific task or when an event occurs.
function processData(data, callback) {
var processedData = data + " processed";
callback(processedData);
}
function displayData(data) {
console.log("Data:", data);
}
processData("Input", displayData);- The above code is a simple synchronous callback as it gets executed immediately.
- Call backs are often used after an asyncronous operation has completed.
- For example the inside the
then()block we use a callback function.
A callback is a function passed as an argument to another function.
function myDisplayer(data) {
console.log(data);
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);- Please note function parenthesis should not be used. don't use
myDisplayer()
- We can also write the callback function body while passing it.
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, function (data){
console.log(data);
});
// We can also use arrow function
myCalculator(5, 5, (result)=>{
console.log(result)
});- The below code simulates a API call where the data is fetched with a delay of 2 seconds
- And then the callback function is called.
function fetchData(url, callback) {
setTimeout(function() {
let data = { message: 'Data retrieved successfully' };
callback(null, data);
}, 2000);
}
function processData(error, data) {
if (error) {
console.error('Error:', error);
} else {
console.log('Data:', data);
}
}
fetchData('https://api.example.com/data', processData);- This demonstrates how callback functions help solve the asynchronous nature of the API request.
- Instead of blocking and waiting for the response, the code continues to execute, allowing other tasks to run.
- Once the data is ready, the callback function is called, and the appropriate action can be taken.
- This approach enables non-blocking and efficient execution of code in JavaScript.
- Callback hell, also known as the
pyramid of doom,is a situation that arises - when multiple asynchronous operations are nested within each other using callback functions.
- This can result in deeply nested and indented code, making it difficult to read, understand, and maintain.
const data = ['Cheese', 'Milk', 'Butter'];
function createOrder(result1, callback) {
setTimeout(function() {
callback(result1);
}, 1000);
}
function showOrderSummary(result2, callback) {
setTimeout(function() {
callback(result2.sort());
}, 1000);
}
function updateWallet(result3, callback) {
setTimeout(function() {
callback(result3);
}, 1000);
}
createOrder(data, function(result1) {
console.log('Order created:', result1);
showOrderSummary(result1, function(result2) {
console.log('Order summary:', result2);
updateWallet(result2, function(result3) {
console.log('Wallet updated:', result3);
});
});
});- The
createOrderfunction is called with the data parameter and a callback function. - Inside the callback function, the
showOrderSummaryfunction is called with another callback function. - Within that callback, the
updateWalletfunction is called with a final callback function. - This structure represents the callback hell scenario, with multiple levels of nested callbacks.
- This is an anti pattern and we should use alternative approaches like Promises or async/await