JavaScript Promises provide a way to handle asynchronous operations. They represent an operation's eventual completion (or failure) and its resulting value. Let's explore a basic example to understand how Promises work.
Creating a Simple Promise
// Creating a new Promise
const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => {
    const data = "Hello, this is your data!";
    const error = false;
    if (!error) {
      resolve(data);
    } else {
      reject("An error occurred while fetching data.");
    }
  }, 2000); // it will run after  2-second 
});
console.log("Fetching data...");
fetchData
  .then((result) => {
    console.log("Data received:", result);
  })
  .catch((error) => {
    console.error("Error:", error);
  })
  .finally(() => {
    console.log("Operation complete.");
  });
In this example:
- We create a new Promise using the Promise constructor, which takes a function with two parameters: resolveand reject.
- Inside this function, we simulate an asynchronousoperation usingsetTimeout.
- After 2 seconds, we check if an error occurred
-  If no error, we call resolve(data)to mark the promise as fulfilled
- with the data.
-    If there's an error, we call reject(errorMessage)to mark the
-    promise as rejected with an errorMessage.
- We handle the promise using .then(), .catch(), and .finally()
- .then()is called when the promise is fulfilled.
- .catch()is called when the promise is rejected.
- .finally()is called when the promise is settled (either fulfilled or rejected).
When you run the above code, the console will display.
Fetching data...
// After 2 seconds
Data received: Hello, this is your data!
Operation complete.
If you change const error = false; to const error = true;, the output will be
Fetching data...
// After 2 seconds
Error: An error occurred while fetching data.
Operation complete.
 
 
              

 
    
Top comments (1)
Hello! I'm a big fan of Promises and always love to see more articles about them!
Your initial image appears to have an error where I think the final yellow box should be listed as "Settled" and contain
.finally().Also, it's not required but generally the object passed in a
rejectis anErrorrather than just a string. This one is more of a convention, because promises that are rejected due to an actual exception will contain an Error. I have certainly passed strings in rejected promises in the past, but looking back at that code I wish I had been consistent in the use of Error objects.