Data Analytics
## 🔹 Practical Example: Interactive Todo List // DOM Elements const form = document.querySelector('#todo-form'); const input = document.querySelector('#todo-input'); const list = document.querySelector('#todo-list'); // Add new todo form.addEventListener('submit'…
# 📚 JavaScript Tutorial - Part 5/10: Asynchronous JavaScript
#JavaScript #Async #Promises #FetchAPI #WebDev
Welcome to Part 5 of our JavaScript series! Today we'll conquer asynchronous programming - the key to handling delays, API calls, and non-blocking operations.
---
## 🔹 Synchronous vs Asynchronous
### 1. Synchronous Execution
### 2. Asynchronous Execution
---
## 🔹 Callback Functions
Traditional way to handle async operations.
### 1. Basic Callback
### 2. Callback Hell (The Pyramid of Doom)
---
## 🔹 Promises (ES6)
Modern solution for async operations.
### 1. Promise States
- Pending: Initial state
- Fulfilled: Operation completed successfully
- Rejected: Operation failed
### 2. Creating Promises
### 3. Using Promises
### 4. Promise Chaining
### 5. Promise Methods
---
## 🔹 Async/Await (ES8)
Syntactic sugar for promises.
### 1. Basic Usage
### 2. Parallel Execution
---
## 🔹 Fetch API
Modern way to make HTTP requests.
### 1. GET Request
### 2. POST Request
### 3. Error Handling
---
## 🔹 Practical Example: Weather App
---
## 🔹 AJAX with XMLHttpRequest (Legacy)
Older way to make requests (still good to know).
#JavaScript #Async #Promises #FetchAPI #WebDev
Welcome to Part 5 of our JavaScript series! Today we'll conquer asynchronous programming - the key to handling delays, API calls, and non-blocking operations.
---
## 🔹 Synchronous vs Asynchronous
### 1. Synchronous Execution
console.log("Step 1");
console.log("Step 2"); // Waits for Step 1
console.log("Step 3"); // Waits for Step 2### 2. Asynchronous Execution
console.log("Start");
setTimeout(() => {
console.log("Async operation complete");
}, 2000);
console.log("End");
// Output order: Start → End → Async operation complete---
## 🔹 Callback Functions
Traditional way to handle async operations.
### 1. Basic Callback
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData((data) => {
console.log(data); // "Data received" after 1 second
});### 2. Callback Hell (The Pyramid of Doom)
getUser(user => {
getPosts(user.id, posts => {
getComments(posts[0].id, comments => {
console.log(comments); // Nested nightmare!
});
});
});---
## 🔹 Promises (ES6)
Modern solution for async operations.
### 1. Promise States
- Pending: Initial state
- Fulfilled: Operation completed successfully
- Rejected: Operation failed
### 2. Creating Promises
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
success ? resolve("Data fetched!") : reject("Error!");
}, 1500);
});### 3. Using Promises
fetchData
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log("Done!"));
### 4. Promise Chaining
fetchUser()
.then(user => fetchPosts(user.id))
.then(posts => fetchComments(posts[0].id))
.then(comments => console.log(comments))
.catch(error => console.error(error));
### 5. Promise Methods
Promise.all([promise1, promise2]) // Waits for all
Promise.race([promise1, promise2]) // First to settle
Promise.any([promise1, promise2]) // First to fulfill
---
## 🔹 Async/Await (ES8)
Syntactic sugar for promises.
### 1. Basic Usage
async function getData() {
try {
const response = await fetchData();
console.log(response);
} catch (error) {
console.error(error);
}
}### 2. Parallel Execution
async function fetchAll() {
const [users, posts] = await Promise.all([
fetchUsers(),
fetchPosts()
]);
console.log(users, posts);
}---
## 🔹 Fetch API
Modern way to make HTTP requests.
### 1. GET Request
async function getUsers() {
const response = await fetch('https://api.example.com/users');
const data = await response.json();
return data;
}### 2. POST Request
async function createUser(user) {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
});
return response.json();
}### 3. Error Handling
async function safeFetch(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(response.status);
return await response.json();
} catch (error) {
console.error("Fetch failed:", error);
}
}---
## 🔹 Practical Example: Weather App
async function getWeather(city) {
try {
const apiKey = 'YOUR_API_KEY';
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
);
if (!response.ok) throw new Error('City not found');
const data = await response.json();
return {
temp: Math.round(data.main.temp - 273.15), // Kelvin → Celsius
conditions: data.weather[0].main
};
} catch (error) {
console.error("Weather fetch error:", error);
return null;
}
}
// Usage
const weather = await getWeather("London");
if (weather) {
console.log(`Temperature: ${weather.temp}°C`);
console.log(`Conditions: ${weather.conditions}`);
}---
## 🔹 AJAX with XMLHttpRequest (Legacy)
Older way to make requests (still good to know).