Week 3
3.8 Asynchronous javaScript & APIs
Week 3
3.8 Asynchronous javaScript & APIs
Asynchronous JavaScript & APIs
JavaScript is single-threaded, meaning it executes one operation at a time. But what if we need to fetch data from an API, wait for a response, or execute a time-consuming task without freezing the page?
That’s where Asynchronous JavaScript comes in!
Synchronous code executes line by line, meaning each statement waits for the previous one to finish before executing.
console.log("Task 1");
console.log("Task 2");
console.log("Task 3");
Output:
Task 1
Task 2
Task 3
Simple, but imagine if Task 2 took 5 seconds! It would block everything.
Asynchronous code doesn’t wait for long-running tasks to finish before moving on.
console.log("Task 1");
setTimeout(() => {
console.log("Task 2 (delayed)");
}, 2000);
console.log("Task 3");
Output:
Task 1
Task 3
Task 2 (delayed) <-- Runs after 2 seconds!
The setTimeout() function allows the program to continue running without waiting!
Before modern JavaScript, callbacks were used to handle asynchronous tasks.
function fetchData(callback) {
setTimeout(() => {
callback("Data received!");
}, 2000);
}
fetchData((message) => {
console.log(message); // Output: Data received! (after 2 sec)
});
Problem? Callbacks can become nested inside each other—this is called Callback Hell!
fetchData((data) => {
console.log(data);
fetchData((data2) => {
console.log(data2);
fetchData((data3) => {
console.log(data3);
});
});
});
Hard to read, debug, and maintain!
A Promise is an object that represents the eventual completion of an asynchronous task. It can be:
✅ fulfilled → Task completed successfully
❌ rejected → Something went wrong
⏳ pending → Still waiting
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
let success = true;
if (success) {
resolve("Promise resolved!");
} else {
reject("Promise rejected");
}
}, 2000);
});
How to Use a Promise?
myPromise
.then((message) => {
console.log(message); // Output: Promise resolve
})
.catch((error) => {
console.log(error); // Output: Promise rejected (if error)
});
.then() handles success
.catch() handles errors
async and await make working with Promises cleaner and more readable!
async function fetchData() {
try {
let response = await myPromise; // Wait until the promise resolves
console.log(response);
} catch (error) {
console.log(error);
}
}
fetchData();
No .then() or .catch(), just a clean try/catch block!
APIs allow web apps to fetch and send data without reloading the page.Fetching Data with .then()
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
async function getPost() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
getPost();
Much cleaner than .then() chaining!
Sometimes, we need to make multiple requests at the same time.
async function getMultiplePosts() {
try {
let [post1, post2] = await Promise.all([
fetch("https://jsonplaceholder.typicode.com/posts/1").then(res => res.json()),
fetch("https://jsonplaceholder.typicode.com/posts/2").then(res => res.json())
]);
console.log(post1, post2);
} catch (error) {
console.error("Error:", error);
}
}
getMultiplePosts();
All requests run at the same time, making it faster!
JavaScript is synchronous but can handle async tasks using Callbacks, Promises, and async/await.
Callbacks were the old way, but they caused Callback Hell.
Promises make async code easier to manage with .then() and .catch().
async/await simplifies Promises, making code cleaner and readable.
Fetch API allows JavaScript to get and send data from APIs.
Promise.all() helps run multiple API requests in parallel.
async function getUsers() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/users");
let users = await response.json();
console.log(users);
} catch (error) {
console.log("Failed to fetch users:", error);
}
}
getUsers();
❓ What happens if the API fails? How can you improve error handling?
🚀 Next Up: JavaScript and the Browser.