(Handle asynchronous tasks like API calls, delays, and file loading)
JavaScript is single-threaded, meaning it executes one task at a time.
But real-world tasks (like fetching data or waiting for a timer) can take time.
Asynchronous programming lets your code continue running without blocking.
function getData(callback) {
setTimeout(() => {
callback("Data loaded");
}, 1000);
}
getData((result) => {
console.log(result); // Data loaded
});⚠️ Problem: Callback Hell — nested callbacks are hard to read and debug.
A Promise is an object that represents the future value of an async operation.
const myPromise = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if (success) resolve("Success!");
else reject("Error occurred");
}, 1000);
});myPromise
.then((value) => {
console.log(value); // Success!
})
.catch((error) => {
console.error(error);
})
.finally(() => {
console.log("Promise completed");
});fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => console.error(err));async makes a function return a promise.
await waits for the promise to resolve.
async function getPost() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log(data);
} catch (err) {
console.error("Error:", err);
}
}
getPost();More readable than .then() chaining.
setTimeout(() => {
console.log("Runs after 2 seconds");
}, 2000);
let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log(counter);
if (counter === 3) clearInterval(intervalId);
}, 1000);const p1 = Promise.resolve("First");
const p2 = Promise.resolve("Second");
Promise.all([p1, p2]).then(values => console.log(values)); // [ "First", "Second" ]
Promise.race([p1, p2]).then(value => console.log(value)); // "First" (whichever resolves first)async/await makes code cleaner and easier to read.catch() or try...catch to handle errors.Promise.all waits for all promises; Promise.race returns the first one.fetch() to get a list of users from a public API.await to fetch and display data.try...catch with async/await..then() methods to process fetched data.