DEV Community

Pavithraarunachalam
Pavithraarunachalam

Posted on

Today learned about promise in javascript.

what is promise in javascript?

In JavaScript, a Promise is an object representing the eventual completion or failure of an asynchronous operation and its resulting value. It provides a structured way to handle asynchronous code, making it more manageable and readable than traditional callback-based approaches.

Basic Syntax:

const login =new promise((resolve,reject)=>{
let pass=true;
if(pass)
{
resolve();
}
else{
reject();
}
})

States of a Promise:

  1. Pending – Initial state, neither fulfilled nor rejected.
  2. Fulfilled – The operation completed successfully.
  3. Rejected – The operation failed.

Creating a Promise:

A new Promise is created using the Promise constructor. This executor function receives two arguments: resolve andreject.

resolve(value) — called when the operation succeeds

reject(error) — called when it fails
Enter fullscreen mode Exit fullscreen mode

Once you call either resolve or reject, the promise becomes settled (fulfilled or rejected) and cannot change.

Example:

<script>


     function login(){
        return new Promise((resolve,reject)=>{
        let password = true;
        if(password){
            resolve();
        }else{
            reject();
        }
    })
    }

    login()
    .then(()=> console.log("successfully login..."))
    .catch(()=>  console.log("invalid password..."))


</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)