Here’s the content you provided, regenerated:
In synchronous JavaScript programming, code runs sequentially, one line at a time. However, for handling asynchronous tasks like API calls or reading files, callbacks and promises come into play to avoid blocking the execution of code.
- Callback
A callback is a function passed as an argument to another function. It is executed after the completion of that function, enabling asynchronous code execution.
Example:
function fetchData(callback) {
setTimeout(() => {
console.log("Data fetched");
callback();
}, 2000);
}
function processData() {
console.log("Processing data...");
}
fetchData(processData);
Here, fetchData takes processData as a callback, ensuring processData runs after fetchData completes.
- Promises
A promise represents a value that may be available now, later, or never. It has three states:
Pending: The initial state.
Fulfilled: The operation completed successfully.
Rejected: The operation failed.
Example:
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve("Data fetched");
} else {
reject("Error fetching data");
}
}, 2000);
});
fetchData
.then((result) => {
console.log(result);
// Continue processing data
})
.catch((error) => {
console.log(error);
});
This example uses a promise that either resolves (fetches data) or rejects (throws an error) after 2 seconds.
Promises are a more modern and cleaner way to handle asynchronous operations than callbacks. They can be chained and are often used with async/await for even more readability.
Asynchronous programming in JavaScript allows you to perform tasks like making API calls, reading files, or querying databases without blocking the execution of other code. This is crucial in web development for maintaining responsiveness and performance.
Key Concepts
- Callbacks: A function passed as an argument to another function, executed after an asynchronous operation completes.
Example:
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched");
}, 1000);
}
fetchData((data) => {
console.log(data);
});
- Promises: An object that represents the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, or rejected.
Example:
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched");
}, 1000);
});
promise
.then((data) => console.log(data))
.catch((error) => console.log(error));
- Async and Await: async functions return a promise and simplify promise handling. await pauses execution in an async function until the promise is resolved.
Example:
async function fetchData() {
try {
let data = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched");
}, 1000);
});
console.log(data);
} catch (error) {
console.log(error);
}
}
fetchData();
Asynchronous Patterns
Callback Hell: Nesting callbacks within other callbacks, making the code harder to read.
Promise Chaining: Avoids callback hell by chaining .then() and .catch() for better readability.
Async/Await: A cleaner, modern approach, making asynchronous code look synchronous.
Use Cases
API Calls: Fetching data from a server.
Timers: Using setTimeout or setInterval.
File Operations: Reading or writing files non-blockingly.
Event Handling: Handling user interactions like clicks or keypresses.
Asynchronous programming in JavaScript is vital for building responsive, efficient applications, especially when handling I/O-bound operations.