DEV Community

Dharshini E
Dharshini E

Posted on

Javascript - promises

Promises:

  • Promises is object .
  • using new keyword create promises.

syntax:

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

  myResolve(); // when successful
  myReject();  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);
Enter fullscreen mode Exit fullscreen mode
  • resolve and rejectt are callback functions .
  • promises get two arguments like resolve and reject .
  • promises return resolve and reject functions.

Promises have three states:
Pending:
The initial state. The asynchronous operation is still in progress, and the promise is neither fulfilled nor rejected.
Fulfilled (or Resolved):
The state when the asynchronous operation successfully completes. The promise holds a resulting value.
Rejected:
The state when an error occurs during the asynchronous operation. The promise holds a reason for the failure (an error object).

Example:

const ticket= new Promise((resoleve,reject)=>{
        let bookingresult=true;
        if(bookingresult){
            resoleve(850);
        }
        else{
            reject();
        }
       });

       //procress of promise
     ticket.then((succuss)=>{
             console.log("booking susccessfully!");

       })
       .catch((failure)=>{
        console.log("booking failure!");

       });

       //reslove parameter get 
       ticket.then((amt)=>{
        console.log("amount is" +amt);
       })
       .catch(()=>{
        console.log("failure");

       });
Enter fullscreen mode Exit fullscreen mode

.then(onFulfilled, onRejected): **
This method takes two optional callback functions. onFulfilled is called if the promise is fulfilled, receiving the resolved value. onRejected is called if the promise is rejected, receiving the error reason.
**.catch(onRejected):

This is a shorthand for .then(null, onRejected) and is commonly used for error handling.

Top comments (0)