What is Promises in javascript?

In JavaScript, a Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. Promises provide a cleaner and more structured way to handle asynchronous operations compared to callbacks. They are a key feature introduced in ECMAScript 2015 (ES6) and are widely used in modern JavaScript development.

A Promise can be in one of three states:

  1. Pending: The initial state; the promise is neither fulfilled nor rejected.
  2. Fulfilled (Resolved): The asynchronous operation completed successfully, and the promise has a resulting value.
  3. Rejected: The asynchronous operation encountered an error or was unsuccessful, and the promise has a reason for the failure.

Here is a basic example of a Promise:

const myPromise = new Promise((resolve, reject) => {
  // Simulating an asynchronous operation (e.g., fetching data from an API)
  setTimeout(() => {
    const success = true;

    if (success) {
      resolve('Operation successful');
    } else {
      reject('Operation failed');
    }
  }, 2000); // Resolves or rejects after 2 seconds
});

// Using the Promise
myPromise
  .then((result) => {
    console.log('Success:', result);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

In this example:

  • The Promise constructor takes a single argument, a function with two parameters: resolve and reject. These are functions provided by the Promise implementation to either fulfill or reject the promise.
  • Inside the function, you perform an asynchronous operation (e.g., fetching data). When the operation is complete, you call resolve with the result if successful or reject with an error if there’s a failure.
  • The then method is used to handle the fulfilled state, and the catch method is used to handle the rejected state.

Promises can be chained together, allowing for more complex and readable asynchronous code. They also provide a cleaner alternative to the callback pyramid problem often associated with callback-based asynchronous code. In addition to then and catch, Promises offer other methods such as finally, all, and race to handle multiple promises simultaneously.

As of ECMAScript 2018 (ES9), JavaScript also introduced async/await syntax, which simplifies working with Promises by allowing developers to write asynchronous code in a more synchronous style.

Promises in javascript is used to handle the asynchronus task. Promises in javascript has producing code and consuming code to handle. it means consuming code has to be wait until code can not be produce either with sucess or with error

Promises method is used to handle the promises

Syantax :

new Promise(sucessmethod,errormethod)

Promise object has two call back function. one is sucessmethod and another has errormethod.on sucess of promise sucessmethod will get call while errormethod will get call after an error in promise

Promises methods

  • promise.then()
  • promise.catch()
  • promise.finally()

then() method in promise

then() method has also two call back function one is on sucess and another is on error.similary nested then() method work

let promise=new Promise(sucessmethod,errormethod();
promise.then(sucessmethod,errormethod)


simliarly nested then() method is used to handle the next promise object created by then() method until catch() method is not called

Example


let promise=new Promise(sucessmethod,errormethod();
promise
.then(sucessmethod,errormethod) //this will handle the promise that we have created
.then() //this will handle the promise object that is created by previous then() method
.then() //simliarly a chain of than() method is called until we can't react catch() method


Syntax of catch() method:

promise1
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { console.log(value) })
.catch(err => { console.log(errr) });

Syntax of finally() method:

promise1
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { console.log(value) })
.catch(err => { console.log(errr) })
.finally();

finally method with catch method Example:

function numbercheck() {
  return new Promise((resolve, reject) => {
    if (Math.random() > 5) {
      resolve('number is greater than ');
    } else {
      reject(new Error('number is less than 5'));
    }
  });
}

numbercheck()
  .then((number) => {
    console.log(number);
  })
  .catch((err) => {
    console.error(err);
  })
  .finally(() => {
    console.log(' process done');
  });

Leave a Comment