Asynchronous JavaScript is a way to handle tasks that take a long time to complete, without blocking other tasks in the application. Here are some examples of how to use asynchronous JavaScript in practice:
1- Callback functions: A callback function is a function that is passed as an argument to another function and is called after that function completes its task. For example:javascript
function fetchData(callback) {
setTimeout(() => {
const data = { name: 'John', age: 30 };
callback(data);
}, 2000);
}
function displayData(data) {
console.log(`Name: ${data.name}, Age: ${data.age}`);
}
fetchData(displayData);
In this example, fetchData() is a function that simulates fetching data from a server with a 2-second delay using setTimeout(). It accepts a callback function as an argument, which is called with the data after the delay. displayData() is the callback function that logs the data to the console.
javascript
function fetchData() {
return new Promise(resolve => {
setTimeout(() => {
const data = { name: 'John', age: 30 };
resolve(data);
}, 2000);
});
}
fetchData().then(data => {
console.log(`Name: ${data.name}, Age: ${data.age}`);
});
In this example, fetchData() returns a Promise that resolves with the data after a 2-second delay. The then() method is used to handle the resolved value and log it to the console.
javascript
function fetchData() {
return new Promise(resolve => {
setTimeout(() => {
const data = { name: 'John', age: 30 };
resolve(data);
}, 2000);
});
}
async function displayData() {
const data = await fetchData();
console.log(`Name: ${data.name}, Age: ${data.age}`);
}
displayData();
In this example, fetchData() returns a Promise that resolves with the data after a 2-second delay. displayData() is an async function that waits for the Promise to resolve using the await keyword and then logs the data to the console.
These are just a few examples of how to use asynchronous JavaScript in your code. Asynchronous programming can be challenging to master, but it's essential for building performant and responsive applications.


0 Comments