JavaScript Promises

Sudhanshu Gaikwad - Jul 27 - - Dev Community

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.

Image description

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.");
  });

Enter fullscreen mode Exit fullscreen mode

In this example:

  1. We create a new Promise using the Promise constructor, which takes a function with two parameters: resolve and reject.
  2. Inside this function, we simulate an asynchronousoperation using setTimeout.
  3. 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.
  1. 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.

Enter fullscreen mode Exit fullscreen mode

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.

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player