0% found this document useful (0 votes)
3 views10 pages

Java Script Day 6 Notes

The document explains the differences between synchronous and asynchronous programming in JavaScript, highlighting their characteristics, use cases, and examples. It discusses the concept of Callback Hell and provides solutions to avoid it, such as using named functions and Promises. Additionally, it covers the use of Promises and Async/Await for managing asynchronous operations more effectively.

Uploaded by

iti490orizzonte
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)
3 views10 pages

Java Script Day 6 Notes

The document explains the differences between synchronous and asynchronous programming in JavaScript, highlighting their characteristics, use cases, and examples. It discusses the concept of Callback Hell and provides solutions to avoid it, such as using named functions and Promises. Additionally, it covers the use of Promises and Async/Await for managing asynchronous operations more effectively.

Uploaded by

iti490orizzonte
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

1|Page

Synchronous and Asynchronous in JavaScript


JavaScript executes code in two ways:
 Synchronous (Blocking)
 Asynchronous (Non-Blocking)
Synchronous Programming
In synchronous execution, code runs line by line, one after another.
Each task must finish before the next task starts.
Characteristics

 Blocking
 Sequential execution
 Simple to understand
 Can cause delays if task is slow
Example
[Link]("Start");
[Link]("Task 1");
[Link]("Task 2");
[Link]("End");
Asynchronous Programming
In asynchronous execution, long tasks run in the background while
other code continues. Non-blocking behavior.
Characteristics

 Non-blocking
 Improves performance
 Keeps UI responsive
 Used for time-consuming tasks
2|Page

Example with setTimeout


[Link]("Start");
setTimeout(() => {
[Link]("Task 1");
}, 2000);

[Link]("End");
Output
Start
End
Task 1
Where Asynchronous Programming is Used

 API calls
 File operations
 Database queries
 Timers
 User input
Asynchronous Techniques in JavaScript
 Callbacks
 Promises
 Async/Await

Synchronous vs Asynchronous
3|Page

Feature Synchronous Asynchronous

Execution Sequential Parallel / Background

Blocking no yes

Performance Lower for heavy tasks Higher

Complexity Simple More complex

Use case Small tasks Long operations

Callback Hell in JavaScript


Callback Hell occurs when multiple asynchronous operations are nested
inside callbacks, making code difficult to read, maintain, and debug. Also
called “Pyramid of Doom” because of its deep nested structure.
What is a Callback?
A callback is a function passed as an argument to another function
and executed later.
function greet(name, callback) {
[Link]("Hello " + name);
callback();
}

greet("Ram", function () {
[Link]("Welcome!");
});
What is Callback Hell?
When callbacks are nested inside callbacks repeatedly.
4|Page

Example of Callback Hell


setTimeout(() => {
[Link]("Step 1");

setTimeout(() => {
[Link]("Step 2");

setTimeout(() => {
[Link]("Step 3");

setTimeout(() => {
[Link]("Step 4");
}, 1000);

}, 1000);

}, 1000);

}, 1000);

Structure
Step 1
Step 2
5|Page

Step 3
Step 4
Deep nesting → hard to understand
Why Callback Hell is Bad?
 Poor readability
 Difficult debugging
 Hard maintenance
 Error handling becomes complex
 Code reuse becomes difficult

How to Avoid Callback Hell


Use Named Functions
Instead of anonymous nested functions.
function step4() {
6|Page

[Link]("Step 4");
}
function step3() {
[Link]("Step 3");
setTimeout(step4, 1000);
}
function step2() {
[Link]("Step 2");
setTimeout(step3, 1000);
}
setTimeout(step2, 1000);

Promises in JavaScript
A Promise is an object that represents the result of an asynchronous
operation that may complete now, later, or fail. Used to handle
asynchronous tasks more cleanly than callbacks.
Why Promises?

 Avoid Callback Hell


7|Page

 Better readability
 Easier error handling
 Supports chaining
 Foundation for Async/Await
Promise States
A Promise has three states:
State Meaning

Pending Initial state (operation not completed)

Fulfilled Operation completed successfully

Rejected Operation failed

Creating a Promise
Syntax
let promise = new Promise(function(resolve, reject) {
// async operation
});
 resolve() → success
8|Page

 reject() → failure
Example
let p = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation Successful");
} else {
reject("Operation Failed");
}
});
Consuming a Promise
Using .then() and .catch().
[Link](result => {
[Link](result);
}).catch(error => {
[Link](error);
});

Promise Chaining
Multiple asynchronous steps in sequence.
[Link](result => {
[Link](result);
return "Step 2";
})
9|Page

.then(step2 => {
[Link](step2);
});
Each .then() receives previous result.
Finally Block
Runs regardless of success or failure.
[Link](() => {
[Link]("Operation completed");
});

Use Async/Await (Best Modern Solution)


Makes asynchronous code look like synchronous code.
function HEllo(getid) {
return new Promise((resolve, reject) => {
setTimeout(() => {
[Link](getid)
resolve("success")
10 | P a g e

}, 7000);
})
}

async function FeatchID() {


await HEllo(1)
await HEllo(2)
await HEllo(3)
}

Real-Life Uses (Where It Appears)


 API request chains
 Event-driven systems
 Authentication flows
 Payment processing

You might also like