-
JS Setting Up Environment
-
JS Syntax
-
JS Comments
-
JS Generating OutPut
-
JS Variables
-
JS Data Types
-
JS String
-
JS String Methods & Properties
-
JS Template Literals
-
JS Operators
-
JS Conditional Statements
-
JS Break and Continue
-
JS Functions
-
JS DOM
-
JS DOM Methods and Elements
-
JS DOM HTML/CSS Manipulation
-
JS DOM Navigation & Nodes
-
JS Events
-
JS Array
-
JS Loops
-
JS Object
-
JS Accessors
-
JS Object Constructors
-
JS Prototype & Iterables
-
JS Date & Time Function
-
JS Math Function
-
JS Storage
-
JS Classes
-
JS Map & Set
-
JS Global Scope
-
JS Rest and Spread
-
JS Error Handling
-
JS Asynchronous
-
JS Promise
-
JS Async/Await
-
JS Node.js
-
JS Regular Expression
-
JS Fetch API
-
JS BOM
-
JS Form Validation
-
JS Practiced Example
-
JS Projects
Promise
A Promise in JavaScript is a powerful mechanism for handling asynchronous operations. It represents a value that may be available now, or in the future, or never. Promises have three states:
1. Pending: The initial state. The operation is not completed yet.
2. Fulfilled: The operation is completed successfully, and the promise has a resulting value.
3. Rejected: The operation failed, and the promise has a reason for the failure.
Promises are commonly used when dealing with asynchronous tasks, such as making API calls or handling data fetching.
Creating a Promise:
To create a promise, you use the `Promise` constructor, which takes a function as an argument. This function, in turn, takes two parameters: `resolve` and `reject`. If the asynchronous operation is successful, you call `resolve` with the result. If it fails, you call `reject` with an error.
Example:
Using a Promise:
Once you have a promise, you can use the `.then()` method to handle the fulfillment of the promise or the `.catch()` method to handle any rejection.
Example:
countValue.then(
function(value) {
document. write(“Success:”, value);
},
function(error) {
console.error(“Error:”, error);
}
);
In this example, if the promise is fulfilled, the success callback is executed, and if it is rejected, the error callback is executed.
Key Points:
– Promises are excellent for managing asynchronous code and handling success or failure.
– They provide a cleaner alternative to callback functions, making code more readable and maintainable.
– Promises can be chained together for more complex asynchronous workflows.