Promise in JavaScript...
Chithra Priya

Chithra Priya @chithra_priya

Joined:
Apr 29, 2025

Promise in JavaScript...

Publish Date: Jun 30
0 0

In JavaScript, a Promise is an object representing the eventual completion or failure of an asynchronous operation.

Promise have 3 states:

1.Pending - Initial state, (waiting for response)
2.Fulfill- Operation completed successfully (resolve() was called)
3.Rejected - Operation failed (reject() was called)

Syntax for promise:

const promise = new Promise((resolve, reject) => {
  if (success) {
    resolve(result);  
  } else {
    reject(error);    
  }
});

Enter fullscreen mode Exit fullscreen mode
  • resolve: Call this when the task is successful
  • reject: Call this when the task fails

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

Output:

Image description

Comments 0 total

    Add comment