Asynchronous Programming
⏳Asynchronous programming allows your code to execute operations without blocking the main thread, enabling non-blocking execution and better performance, especially in operations like I/O (e.g., file reading, network requests).
Asynchronous operations allow your JavaScript code to perform time-consuming tasks like HTTP requests, file processing, or waiting for user input without freezing the browser or server. This is crucial for creating smooth and responsive applications.
A callback
function is a function that is passed as an argument to another function and is executed after the completion of an asynchronous task.
// Example 1: Using Callback Function
function fetchData(callback) {
setTimeout(() => {
console.log("Data fetched!");
callback();
}, 2000);
}
function processData() {
console.log("Processing data...");
}
fetchData(processData);
A Promise
represents the eventual completion or failure of an asynchronous operation. It allows chaining of asynchronous tasks, helping to avoid callback hell.
// Example 2: Using Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Data fetched!");
resolve("Data");
}, 2000);
});
}
fetchData()
.then((data) => {
console.log(data); // "Data"
console.log("Processing data...");
})
.catch((error) => {
console.log("Error:", error);
});
async/await
is a modern way to handle asynchronous operations, making asynchronous code easier to read and write. It is built on top of promises.
// Example 3: Using Async/Await
async function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Data fetched!");
resolve("Data");
}, 2000);
});
}
async function processData() {
const data = await fetchData();
console.log(data); // "Data"
console.log("Processing data...");
}
processData();
Click to see how asynchronous programming works with Promises:
async/await
is preferred for handling asynchronous tasks in modern JavaScript. It makes the code more readable and reduces nested callbacks.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!