Middle
What is the role and function of a Callback?
sobes.tech AI
Answer from AI
A callback is a function that is passed to another function as an argument and is invoked after the completion of a specific action or event. The main role of a callback is to ensure asynchronous execution of code, allowing the program not to block and to respond to events, such as data loading completion or user actions.
Example in JavaScript:
function fetchData(callback) {
setTimeout(() => {
const data = { name: 'John' };
callback(data); // call callback after data is received
}, 1000);
}
fetchData(function(result) {
console.log('Data received:', result);
});
In this example, the callback function is called after simulating an asynchronous operation (data loading). This allows handling the result when it is ready.