Asynchronous Programming
Asynchronous Programming
What is a Callback?
A callback is a function that is passed as an argument to another function.
Callbacks are mostly used for asynchronous operations (like reading files,
making API calls, or timers).
function sayGoodbye() {
console.log("Goodbye!");
}
greet("Sai", sayGoodbye);
3. Inside greet() , we first print "Hello, Sai", then call the callback() , which prints
"Goodbye!".
📌 Output:
Asynchronous Programming 1
Hello, Sai
Goodbye!
function fetchData(callback) {
console.log("Fetching data...");
setTimeout(() => {
console.log("Data received!");
callback(); // Calling the callback function after data is received
}, 2000);
}
function processData() {
console.log("Processing data...");
}
fetchData(processData);
📌 Output:
Fetching data...
(Data comes after 2 seconds)
Asynchronous Programming 2
Data received!
Processing data...
setTimeout(() => {
console.log("Task 1 done");
setTimeout(() => {
console.log("Task 2 done");
setTimeout(() => {
console.log("Task 3 done");
}, 1000);
}, 1000);
}, 1000);
Asynchronous Programming 3
Summary
1. A callback is a function passed as an argument to another function and is
executed later.
3. Too many nested callbacks lead to Callback Hell, making code hard to read.
1️⃣ What is
.then()
.then() in Promises?
is used to handle the result of a Promise when it resolves (succeeds).
promise.then((data) => {
console.log(data); // "Data received!" (after 2 seconds)
});
✅ How It Works?
resolve("Data received!") means the promise is fulfilled.
.then((data) => {...}) runs after the promise is resolved and receives the resolved
value ( "Data received!" ).
Asynchronous Programming 4
Example of Fetching Data
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json()) // Convert response to JSON
.then((data) => console.log(data)) // Log the data
.catch((error) => console.error("Error:", error));
✅ Breaking It Down:
1. fetch("URL") sends a request to the server.
3️⃣Request)
Stopping a Request (Abort a Fetch
Example:
Asynchronous Programming 5
fetch("https://jsonplaceholder.typicode.com/todos/1", { signal })
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Fetch aborted or failed:", error));
✅ How It Works?
controller.abort() stops the request if it’s taking too long.
200 ✅ OK (Success)
201 ✅ Created (New data added)
400 ❌ Bad Request (Wrong request)
401 ❌ Unauthorized (Need login)
404 ❌ Not Found (URL is wrong)
500 ❌ Server Error (Problem on the server)
Example: Checking Response Status
Asynchronous Programming 6
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => {
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${response.statusText}`);
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error(error));
✅ How It Works?
response.ok is true if status is 200-299.
Difference:
Method Converts Response To Example Use Case
.json() JavaScript Object API responses (JSON format)
.text() Plain Text Fetching simple text files
Example of .json()
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json()) // Convert to JSON object
.then((data) => console.log(data)); // Prints JavaScript object
Asynchronous Programming 7
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Example of .text()
fetch("https://example.com/textfile.txt")
.then((response) => response.text()) // Convert to text
.then((data) => console.log(data)); // Prints plain text
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json", // Tells server we are sending JSON
"Authorization": "Bearer myToken123" // Example authentication token
},
body: JSON.stringify({ title: "New Post", body: "Hello World!", userId: 1 })
})
.then(response => response.json())
Asynchronous Programming 8
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
✅ How It Works?
headers send extra information (like "Content-Type": "application/json" ).
🚀 Final Recap
1️⃣ is used to handle promise results.
.then()
Running a timer ⏳
JavaScript does not wait for these tasks to finish. Instead, it keeps running the
next code immediately.
Asynchronous Programming 9
✅ Output:
Next task
Task Complete! (after 3 seconds)
Problem? The second line runs before the first task is done!
📌 Creating a Promise
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Task completed!"); // Successfully finished
}, 2000);
});
✅ How It Works?
The new Promise() runs immediately.
Asynchronous Programming 10
📌 Example with .then()
myPromise.then((message) => {
console.log(message);
});
📌 Explanation
.then((message) => {...}) runs when the promise is resolved.
myPromise
.then((message) => {
console.log(message);
})
Asynchronous Programming 11
.catch((error) => {
console.error(error);
});
📌 Explanation
If success is false , reject() runs.
✅ Output
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
📌 Explanation
1. fetch("URL") sends a request to get data.
Asynchronous Programming 12
2. .then(response => response.json()) converts the response to JavaScript.
Function Purpose
resolve(value) Marks a promise as successful and sends value .
reject(error) Marks a promise as failed and sends error .
.then(successFn) Runs when promise is resolved.
.catch(errorFn) Runs when promise is rejected.
fetch("https://jsonplaceholder.typicode.com/todos/1", { signal })
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Fetch aborted:", error));
✅ Explanation
controller.abort() stops the request if it takes too long.
Asynchronous Programming 13
If stopped, .catch() runs.
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((data) => console.log(data));
✅ Output
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
fetch("https://example.com/file.txt")
.then((response) => response.text())
.then((data) => console.log(data));
✅ Output
Hello, this is a text file!
Code Meaning
Asynchronous Programming 14
200 ✅ Success
201 ✅ Created
400 ❌ Bad Request
401 ❌ Unauthorized
404 ❌ Not Found
500 ❌ Server Error
📌 Example: Checking Status
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => {
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${response.statusText}`);
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error(error));
✅ Explanation
response.ok checks if status is 200-299.
🔟 Final Recap
1️⃣ Promises help with tasks that take time.
2️⃣ /
resolve() control success/failure.
reject()
Asynchronous Programming 15
7️⃣ Status codes tell us if the request was successful or failed.
You open the package and check your food (process the response)
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json()) // Convert response to JSON
.then((data) => console.log(data)) // Print data
.catch((error) => console.error("Error:", error)); // Handle errors
Step-by-Step Breakdown
1️⃣ sends a request to the server.
fetch("URL")
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
console.log(response); // See all response details
});
response.status HTTP status code (e.g., 200 = OK, 404 = Not Found)
response.statusText Text description of the status (e.g., "OK", "Not Found")
response.headers Headers sent by the server
response.url The URL of the fetched resource
response.json() Converts response to JSON (if applicable)
response.text() Reads response as raw text
→ Kitchen is broken 🚨
500 Internal Server Error
Asynchronous Programming 17
200 OK ✅ Data was fetched successfully
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
console.log("Status:", response.status); // e.g., 200
console.log("Status Text:", response.statusText); // e.g., "OK"
});
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json()) // Convert response to JSON
.then((data) => console.log(data)); // Output the JSON data
Asynchronous Programming 18
"body": "This is an example blog post."
}
fetch("https://www.example.com")
.then((response) => response.text()) // Read response as text
.then((data) => console.log(data)); // Output the text content
✅ Example Output:
<html>
<head><title>Example</title></head>
<body>Welcome to my site!</body>
</html>
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
console.log(response.headers);
});
✅ Example Output:
Headers { "content-type": "application/json; charset=utf-8" }
Asynchronous Programming 19
We can use an AbortController for this.
fetch("https://jsonplaceholder.typicode.com/posts/1", { signal })
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log("Request canceled:", error.message));
Final Recap
Concept Meaning
fetch("URL") Makes a request to a server
response.ok true if request was successful
🔥 Quick Summary
1️⃣ is used to request data from a server.
fetch()
2️⃣ The response object contains details like status, headers, and content.
3️⃣ Use to convert JSON data and for plain text responses.
.json() .text()
Asynchronous Programming 20
4️⃣ Check response.status for status codes (200 OK, 404 Not Found, etc.).
5️⃣ Use AbortController to stop a request.
Asynchronous Programming 21