Javascript callback functions
Created By: chatGPT
Callback functions in JavaScript are functions that are passed as arguments to other functions. They allow you to execute code after a specific task has been completed. This is particularly useful for asynchronous operations such as data fetching, where you want to wait for a response before proceeding with further actions.
function fetchData(callback) {
setTimeout(() => {
const data = { name: 'John', age: 30 };
callback(data);
}, 1000);
}
fetchData((data) => {
console.log('Data received:', data);
});
When using callback functions, the code execution can be controlled to ensure that tasks are performed in the correct order. An example is shown below, where the
calculateSum
function runs once the data is fetched.function calculateSum(x, y) {
return x + y;
}
function getDataAndCalculate(callback) {
fetchData((data) => {
const sum = callback(data.age, 10);
console.log('Sum:', sum);
});
}
getDataAndCalculate(calculateSum);
It's important to handle errors when using callbacks, especially in asynchronous scenarios. You can achieve this by passing an error as the first argument to the callback function.
function fetchDataWithError(callback) {
setTimeout(() => {
const error = null;
const data = { name: 'Jane', age: 25 };
callback(error, data);
}, 1000);
}
fetchDataWithError((error, data) => {
if (error) {
console.error('Error fetching data:', error);
return;
}
console.log('Data received:', data);
});
For scenarios requiring multiple asynchronous operations, you can use nested callbacks. However, this can lead to 'callback hell'. To avoid this, consider using Promises or async/await for better readability.
function fetchDataOne(callback) {
setTimeout(() => {
callback('Data from first API');
}, 1000);
}
function fetchDataTwo(callback) {
setTimeout(() => {
callback('Data from second API');
}, 1000);
}
fetchDataOne((data1) => {
console.log(data1);
fetchDataTwo((data2) => {
console.log(data2);
});
});