X

Promises in Javascript

Promises are a way to handle asynchronous operations in JavaScript. A promise represents the eventual completion or failure of an asynchronous operation and its resulting value. Promises provide a cleaner and more organized way to work with asynchronous code compared to traditional callback patterns.

Promises are a way to handle asynchronous operations in JavaScript.
A promise represents the eventual completion or failure of an asynchronous operation and its resulting value. Promises provide a cleaner and more organized way to work with asynchronous code compared to traditional callback patterns.

A promise can be in one of three states:

Pending: The initial state; the promise is neither fulfilled nor rejected.
Fulfilled: The operation completed successfully, and the promise has a resulting value.
Rejected: The operation failed, and the promise has a reason for the failure.
Here's a basic example of creating and using a promise:

// Creating a promise
const myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation, for example, fetching data from an API
  setTimeout(() => {
    const success = true;

    if (success) {
      resolve("Operation completed successfully");
    } else {
      reject("Operation failed");
    }
  }, 2000);
});

// Consuming the promise
myPromise
  .then((result) => {
    console.log("Success:", result);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

In this example:

The Promise constructor takes a function with `resolve` and `reject` parameters. Inside this function, you perform the asynchronous operation. When the operation is successful, you call resolve with the result; otherwise, you call reject with an error.

The then method is used to handle the fulfilment of the promise. It takes a callback function that will be called when the promise is resolved. The catch method is used to handle the rejection of the promise.

Promises also allow chaining multiple asynchronous operations in a more readable way. The async/await was introduced in ES2017, this syntax provides syntactic sugar on top of promises, making asynchronous code even more readable and manageable. Async keyword returns a promise, while await keyword pauses the execution till the promise is resolved or rejected.  Here's an example:

async function fetchData() {
  try {
    const result1 = await asyncOperation1();
    const result2 = await asyncOperation2(result1);
    console.log("Final result:", result2);
  } catch (error) {
    console.error("Error:", error);
  }
}

In this example, asyncOperation1 and asyncOperation2 are asynchronous functions that return promises. The await keyword is used to wait for the resolution of each promise before moving on to the next operation.