Fet P11
Fet P11
Practical 11
Tools Used: Code editor (vs code) and web browser (Google Chrome).
Theory:
A Promise in JavaScript is an object representing the eventual result of an
asynchronous operation. It serves as a placeholder for a value that isn’t yet available,
allowing you to write asynchronous code in a more synchronous-like manner, improving
readability and manageability. Promises can be in one of three states
● Pending: The initial state, representing that the asynchronous operation is still in progress.
● Fulfilled: Indicates that the asynchronous operation completed successfully, and a result
value is available.
● Rejected: Signifies that the asynchronous operation failed, and an error or reason for failure
is available.
Promises provide methods to handle the eventual outcome of the asynchronous operation:
● .then(): This method is called when the promise is fulfilled, allowing you to access the
result value and perform subsequent actions.
● .catch(): This method is called when the promise is rejected, enabling you to handle errors
and prevent program crashes.
● .finally(): This method is called regardless of whether the promise is fulfilled or rejected,
allowing you to perform cleanup actions
● async: This keyword is used to define an asynchronous function. An async function always
returns a Promise, either implicitly or explicitly.
● await: This keyword can only be used inside an async function. It pauses the execution of
the function until the Promise it "awaits" is resolved or rejected. It then resumes
execution, returning the resolved value of the Promise or throwing the rejected error.
Code:
1. Creation of promise and its handling
a. Create a promise that assigns some data to a variable after a specified time interval.
b. If data is successfully assigned, it should be resolved, otherwise it should be rejected.
c. Handle this promise using both ways, then-catch and async await
2. Handling fetching of an API that has users and e-commerce products
a. URL of Users: https://jsonplaceholder.typicode.com/users
b. URL of products: https://dummyjson.com/products
c. Fetch the data using async-await and then-catch methods.
Output:
Objective Achieved: Through this practical, knowledge of promise, the creation of
promise is done. The management of promise and its handling using different ways is
done. The predefined function fetch is tested with different ways of promise
handling.