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.