Callback is a function passed into another function as a parameter. The callback function will be called after completing a certain task. This allows us to control the execution order of tasks and handle asynchronous tasks efficiently.
Let's see a simple example of using callback in JavaScript:
function fetchData(callback) {
// Giả định việc lấy dữ liệu từ API mất 2 giây
setTimeout(function() {
const data = 'Dữ liệu từ API';
callback(data);
}, 2000);
}
function processResponse(response) {
console.log('XỠlý dữ liệu:', response);
}
fetchData(processResponse);
In the above example, we have a fetchData function to retrieve data from an API. This function uses setTimeout to simulate a 2-second delay in retrieving the data. After successfully retrieving the data, this function will call the callback function processResponse and pass the retrieved data to it.
When we call the fetchData function and pass the processResponse function as a callback, the fetchData function will complete execution after 2 seconds and call the callback function processResponse to handle the retrieved data.