Asynchronous JavaScript
Introduction to Asynchronous JavaScript
Understanding how JavaScript handles asynchronous operations.
Callbacks
Functions passed as arguments to handle async results.
Promises
Promises represent the eventual completion (or failure) of an asynchronous operation. Here's an example:
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched successfully!");
}, 2000);
});
fetchData
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
async/await
The async
and await
keywords simplify working with promises:
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
fetchData();