0% found this document useful (0 votes)
7 views5 pages

Ipass 9

The document outlines a React program that demonstrates asynchronous programming using promises, detailing the definition, states, and key methods of promises. It includes a sample code that fetches data from an API and handles loading and error states, showcasing the importance of promises in managing asynchronous operations. The conclusion emphasizes the significance of understanding promises for building responsive and user-friendly applications in modern web development.

Uploaded by

adityasshimpi
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)
7 views5 pages

Ipass 9

The document outlines a React program that demonstrates asynchronous programming using promises, detailing the definition, states, and key methods of promises. It includes a sample code that fetches data from an API and handles loading and error states, showcasing the importance of promises in managing asynchronous operations. The conclusion emphasizes the significance of understanding promises for building responsive and user-friendly applications in modern web development.

Uploaded by

adityasshimpi
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
You are on page 1/ 5

Aaditya Shimpi

Name : Pratik Vishe


Roll No. : 100
T22
Batch : T23 89

Assignment 9

Aim:- Write a react program to implement the concept of Asynchronous programming using
promises

Lo Mapping:- LO5

Theory:-
1. Definition:
A promise is an object that represents the eventual completion or failure of an asynchronous
operation. It allows you to work with asynchronous code in a more manageable way by
providing a structured approach to handling results and errors.
2. States of a Promise:
Promises have three possible states:
- Pending: The initial state, indicating that the asynchronous operation is still ongoing.
- Fulfilled: Indicates that the operation completed successfully, providing a resulting value. -
Rejected: Indicates that the operation failed, providing a reason for the failure (typically an
error).
3. Key Methods:
- then(): This method is used to specify what to do when a promise is fulfilled. It takes a
callback function that receives the resolved value.
- catch(): This method is used to specify what to do when a promise is rejected. It takes a
callback function that receives the error.
- finally(): This method allows you to execute code after the promise is settled, regardless of
its outcome (fulfilled or rejected).
4. Promise Chaining:
Promises can be chained together, meaning that the output of one promise can be the input for
the next. This facilitates a sequence of asynchronous operations, allowing for cleaner code
organization.
5. Integration with React:
In React, promises are commonly used for handling asynchronous data operations, such as
fetching data from APIs. They are typically utilized within lifecycle methods (like
`useEffect`) or event handlers. The asynchronous nature of promises allows React
components to remain responsive while waiting for data to be fetched or processed.
6. Error Handling:
Name : Pratik Vishe
Roll No. : 100
Batch : T23

Promises provide a built-in way to handle errors through the `.catch()` method, which can be
particularly useful for managing errors in asynchronous operations without the need for
extensive try-catch blocks.
7. Async/Await:
The `async/await` syntax, which is syntactic sugar built on top of promises, provides a more
readable and straightforward way to work with asynchronous code in React, allowing you to
write asynchronous code that looks synchronous.
In summary, promises are an essential part of handling asynchronous operations in React,
providing a structured approach to managing the complexities of asynchronous programming.

Program:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>React Async Programming with Promises</title>
<script
src="https://unpkg.com/react/umd/react.development.js"></script>

<script
src="https://unpkg.com/react-dom/umd/reactdom.development.js"></script

>
<script src="https://unpkg.com/babel-
standalone@6/babel.min.js"></script>
<style>
body { font-family: Arial, sans-
serif; margin: 20px;

}
h1 { color:
#333;
}
.loading {
Name : Pratik Vishe
Roll No. : 100
Batch : T23

font-size: 1.5em; color:


#007bff;

}
.error { color:
red;

}
.post {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
} </style>

</head>
<body>
<div id="root"></div>

<script type="text/babel"> const API_URL =


'https://jsonplaceholder.typicode.com/posts';

const App = () => { const [data, setData] =


React.useState([]); const [loading, setLoading] =
React.useState(true);

const [error, setError] = React.useState(null);

const fetchData = () => {


return new Promise((resolve, reject) => {
fetch(API_URL)
.then((response) => {
if (!response.ok) { throw new
Error('Network response was

not ok');
}
Name : Pratik Vishe
Roll No. : 100
Batch : T23

return response.json(); })
.then((data) => resolve(data))

.catch((error) => reject(error)); });


};

React.useEffect(() => { fetchData()

.then((data) => {
setData(data);
setLoading(false);
})
.catch((error) => {
setError(error.message);
setLoading(false);
});
}, []);

return (
<div>
<h1>Asynchronous Data Fetching with Promises</h1>
{loading && <p className="loading">Loading...</p>}
{error && <p className="error">Error: {error}</p>}
{data.length > 0 && (
<div>
{data.map((post) => (
<div className="post" key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
</div>
)}
Name : Pratik Vishe
Roll No. : 100
Batch : T23

</div>
);
};

ReactDOM.render(<App />, document.getElementById('root'));


</script>
</body>
</html>

Output:-

Conclusion:- This React program effectively demonstrates the concept of asynchronous


programming using promises. By leveraging the `fetch` API to retrieve data from an external
source, the application showcases how to handle asynchronous operations smoothly. The use
of promises allows for clear and structured error handling, providing a responsive user
experience. Through the implementation of loading and error states, users are kept informed
of the application’s status, enhancing usability. This example illustrates the importance of
asynchronous programming in modern web development, enabling applications to remain
responsive while performing time-consuming tasks, such as data fetching. Overall,
understanding and utilizing promises in React is essential for building efficient and
userfriendly applications.

You might also like