0% found this document useful (0 votes)
13 views8 pages

JS Promise

The document provides an example of using a promise in JavaScript to handle asynchronous operations. It demonstrates creating a promise with a simulated delay and how to manage its resolved and rejected states using the then and catch methods. The example highlights the basic structure and functionality of promises in JavaScript.

Uploaded by

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

JS Promise

The document provides an example of using a promise in JavaScript to handle asynchronous operations. It demonstrates creating a promise with a simulated delay and how to manage its resolved and rejected states using the then and catch methods. The example highlights the basic structure and functionality of promises in JavaScript.

Uploaded by

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

Certainly!

Here's a concise example of using a promise in JavaScript:

javascript
Copy code
// Creating a simple promise
const myPromise = new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() => {
const success = true; // Change to false to simulate rejection
if (success) {
resolve("Promise resolved successfully!");
} else {
reject("Promise rejected with an error!");
}
}, 2000); // Simulating a delay of 2 seconds
});

// Handling the promise


myPromise
.then((result) => {
[Link](result); // Output if the promise is resolved
})
.catch((error) => {
[Link](error); // Output if the promise is rejected
});
In this example, the promise is created with a simple asynchronous operation using
setTimeout. The then method is used to handle the resolved state, and the catch
method is used to handle the rejected state.

You might also like