Creating a new Promise in JavaScript involves using the Promise constructor. Here's an example of how to create a new Promise:
const myPromise = new Promise((resolve, reject) => {
// Inside this function, you define the asynchronous operation
// For example, you can simulate an async operation with setTimeout
setTimeout(() => {
const success = true; // Replace with your actual logic
if (success) {
resolve("Operation succeeded!"); // Resolve the promise with a value
} else {
reject("Operation failed!"); // Reject the promise with an error
}
}, 2000); // Simulating a delay of 2 seconds
});
// Using the promise
myPromise
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});
In this example, we create a new Promise called myPromise. It takes a function as its argument, which receives two parameters:
resolve and reject. Inside this function, you define your asynchronous operation, which in this case is simulated using
setTimeout.
If the operation is successful, you call resolve and pass the result to it. If it encounters an error, you call
reject and provide an error message or an error object.
You can then use the .then() method to handle the successful outcome when the Promise is resolved and the
.catch() method to handle errors when the Promise is rejected.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Creating a new Promise in JavaScript involves using the Promise constructor. Here's an example of how to create a new Promise:
In this example, we create a new Promise called myPromise. It takes a function as its argument, which receives two parameters: resolve and reject. Inside this function, you define your asynchronous operation, which in this case is simulated using setTimeout.
If the operation is successful, you call resolve and pass the result to it. If it encounters an error, you call reject and provide an error message or an error object.
You can then use the .then() method to handle the successful outcome when the Promise is resolved and the .catch() method to handle errors when the Promise is rejected.