0% found this document useful (0 votes)
21 views21 pages

Class 15 - JavaScript

JavaScript is a single-threaded language, meaning it can only execute one task at a time, which simplifies memory handling but can lead to issues like Callback Hell. To manage asynchronous operations without blocking the UI, JavaScript uses Promises and the async/await syntax, allowing for better readability and error handling. Promises represent future values and can be in one of three states: pending, fulfilled, or rejected.

Uploaded by

kinzaanwarmahar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views21 pages

Class 15 - JavaScript

JavaScript is a single-threaded language, meaning it can only execute one task at a time, which simplifies memory handling but can lead to issues like Callback Hell. To manage asynchronous operations without blocking the UI, JavaScript uses Promises and the async/await syntax, allowing for better readability and error handling. Promises represent future values and can be in one of three states: pending, fulfilled, or rejected.

Uploaded by

kinzaanwarmahar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript

JavaScript Asynchronous Programming


JavaScript is Single-Threaded
👉 JavaScript is single-threaded, which means it can execute only one task at a
time, in a single sequence.
What is a “Thread”?
A thread is like a worker.

● Multi-threaded language → many workers at the same time


● JavaScript → only one worker

Real-life example 🧠

󰞽 One chef in a kitchen:

● He can cook only one dish at a time


● If one dish takes time, others must wait

👉 JavaScript works the same way.


Why is Javascript single-threaded?
✔ Simpler memory handling

✔ No deadlocks

✔ Perfect for browser DOM manipulation


Deadlock Example
Problem : Callback Hell 😵 👉Callback Hell happens
when callbacks are written
doTask1(() => { inside callbacks again and
again.
doTask2(() => { Problems with Callback Hell
doTask3(() => { ❌ Poor readability
❌ Difficult error handling
[Link]("Done"); ❌ Hard to scale code
❌ Difficult maintenance
}); How to avoid Callback Hell?

}); ✔ Use Promises


✔ Use Async / Await
});
Why we need Promises & async/await

JavaScript is single-threaded, but web apps must handle:


● API calls 🌐
● File loading 📂
● Database requests 🗄
● Timers ⏱

These tasks take time → asynchronous operations


We don’t want to block the UI while waiting.
What is a Promise?

● A Promise is an object that represents a value that will be available


in the future.
● A Promise handles future results of asynchronous operations like
API calls, file loading, or timers.
Promise States Real-life example (very easy)

📦 You order food online.


A Promise is always in one of these states:
● Pending → Food is being prepared
1. Pending – Initial state or Operation is in progress

● Fulfilled → Food delivered


2. Fulfilled – Operation completed successfully

● Rejected → Order cancelled


3. Rejected – Operation failed ❌

👉 That order status is exactly how a Promise


📌 Once fulfilled or rejected → state cannot change
works.
Creating a Promise Example
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data received successfully");
Explanation
} else {
● resolve() → success result
reject("Error occurred");
● reject() → error result

} ● Promise executor runs immediately

});
Consuming a Promise (then & catch)
myPromise
.then(result => {
[Link](result); Flow

}) ● .then() → runs on success

.catch(error => { ● .catch() → runs on error

[Link](error);
});
Async / Await
async makes a function always return a Promise
async function getData() {
return "Hello";
}
Equivalent to:
function getData() {
return [Link]("Hello");
}
What is await?
📌await pauses the function execution until the Promise resolves
📌 await can only be used inside async functions

async function fetchData() {


const response = await fetch(url);
What Happens?
const data = await [Link]();
1. JS calls fetch(url)
[Link](data); 2. Function pauses ⏸
} 3. Promise resolves
4. Execution resumes ▶
Async/Await vs Promises (Comparison)

Promise Style Async/Await Style

async function loadData() {


fetch(url) try {
const res = await fetch(url);
.then(res => [Link]())
const data = await [Link]();
.then(data => [Link](data)) [Link](data);
} catch (err) {
.catch(err => [Link](err)); [Link](err);
}
}
Error Handling in Async/Await
Using try...catch
async function getUser() {
try {
const res = await fetch(url);
const data = await [Link]();
[Link](data);
} catch (error) {
[Link]("Error:", error);
}
}
Multiple Promises with [Link]()

const p1 = fetch(url1); With Async/Await


const p2 = fetch(url2);
const p1 = fetch(url1);
[Link]([p1, p2]) const p2 = fetch(url2);
async function loadAll() {
.then(results => { const results = await [Link]([p1, p2]);
}
[Link]("All done");
});

⚡ Runs promises in parallel


MCQs
Q1⃣ What does a Promise represent?
A. Current value

B. Past value

C. Future value

D. Static value

✅ Answer: C

📌 Promise represents a value available in the future.


Q2⃣ Which method handles Promise rejection?
A. then()

B. finally()

C. catch()

D. resolve()

✅ Answer: C
Q3⃣ What is the initial state of a Promise?

A. Fulfilled

B. Pending

C. Rejected

D. Completed

✅ Answer: B
Q4⃣ Which keyword makes a function return a Promise?

A. function

B. return

C. await

D. async

✅ Answer: D
Q5⃣ Where can await be used?
A. Inside async function

B. Only in global scope

C. Anywhere

D. Inside setTimeout

✅ Answer: A

You might also like