Promise in JavaScriptPromise in JavaScript

A Promise in JavaScript is a pattern for handling async operations that makes it easier to write and understand async code. It represents a value that may not be available yet but will be at some point in the future.

The Promise object has 3 states: pending, fulfilled, and rejected. Once a promise is fulfilled or rejected, its value cannot be changed. You can register callback functions (then, catch) to handle the outcome of the promise, once it’s either resolved (fulfilled) or rejected.

This makes async code more manageable and less error-prone compared to using callbacks alone.

Syntax to create a promise

const promise = new Promise((resolve, reject) => {
  // asynchronous operation
  if (operationWasSuccessful) {
    resolve(value);
  } else {
    reject(error);
  }
});

promise
  .then(value => {
    // handle success
  })
  .catch(error => {
    // handle error
  });

In this syntax, you create a Promise object using the Promise constructor, which takes a function as an argument. The function has two parameters, resolve and reject, which are both functions. If the asynchronous operation was successful, you call the resolve function with the result value. If the operation failed, you call the reject function with an error.

You can then use the then method to register a successful callback, which will be called with the resolved value if the Promise is fulfilled. You can use the catch method to register an error callback, which will be called with the error if the Promise is rejected.

Examples

Example 1: Delaying a message:

// Example of promise
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Recursive Minds");
  }, 2000);
});

myPromise
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error);
  });

In this example, myPromise is a Promise that resolves after 2 seconds with the string "Recursive Minds". The then the method is called with a callback function to log the result when the Promise is resolved, and the catch method is called with a callback function to log any errors that may occur.

Example 2: Fetching data from an API:

const fetchData = url => {
  return new Promise((resolve, reject) => {
    fetch(url)
      .then(response => {
        if (!response.ok) {
          reject(response.statusText);
        }
        return response.json();
      })
      .then(data => {
        resolve(data);
      })
      .catch(error => {
        reject(error);
      });
  });
};

fetchData("https://api.example.com/data")
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

In this example, a function fetchData is created that returns a Promise that resolves with data from an API. The fetch function is used to retrieve the data from the API, and the then method is used to check the response status and parse the response as JSON. The resolved data is then logged.

Advantages of promises over callbacks

  1. Better handling of errors: With Promises, error handling is cleaner and easier to understand compared to callbacks, since errors can be caught using the catch method, instead of being passed as a separate argument in a callback.
  2. Improved readability: Promises make it easier to read and understand the flow of async code, since the then and catch methods can be used to chain multiple async operations together in a readable way.
  3. Better composability: Promises can be composed and combined to create complex async flows, without the need for complex callback structures.
  4. Avoiding callback hell: Promises help to avoid the callback hell issue, where the code becomes difficult to read and maintain as the number of nested callbacks increases.
  5. Better debugging: Promises provide better stack traces for errors, making it easier to debug async code.

 

Happy Coding

For more details visit JavaScript.Info

Some other articles on JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *