Learning Outcome: Understand how asynchronous programming works in JavaScript using callbacks.
In JavaScript, there are two main ways your code can run: synchronously and asynchronously. It is crucial to understand how JavaScript callbacks work. Synchronous code runs line by line, finishing each task before moving on to the next. In contrast, asynchronous code can start a task and proceed to others without waiting for it to finish. For example, you can send a text message to a friend and continue doing other things while waiting for their reply.
A callback is a function that you pass to another function as an argument. After the main function completes its task, it calls the callback function to notify you. This method is key in asynchronous programming. Learning about these concepts will help you write better code. For a more detailed look at JavaScript basics, check this lesson.
File: callback_example.js
function fetchData(callback) {
setTimeout(() => {
console.log('Data fetched!');
callback();
}, 2000);
}
function displayData() {
console.log('Displaying data');
}
fetchData(displayData);
Data fetched!
Displaying data
The fetchData function simulates retrieving data using setTimeout. It waits for 2 seconds before logging ‘Data fetched!’ and then calls the displayData function. The callback runs after the asynchronous task completes, illustrating how execution works in JavaScript.
Now, it’s your turn! Create a function named loadData. It should simulate loading data by waiting for 3 seconds, then log ‘Data loading complete!’ After that, call another function, showData, which logs ‘Here is your data!’
function loadData(callback) {
setTimeout(() => {
console.log('Data loading complete!');
callback();
}, 3000);
}
function showData() {
console.log('Here is your data!');
}
loadData(showData);
setTimeout to simulate asynchronous operations effectively.